JS / Jquery - 在json选择器中使用变量 [英] JS/Jquery - using variable in json selector

查看:119
本文介绍了JS / Jquery - 在json选择器中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在从像这样的json源中选择数据时使用变量。
使用jquery getJSON()检索json。

I need to use a variable when selecting data from a json source like this. The json is retrieved with jquery getJSON().

"prices":[{
    "fanta":10,
    "sprite":20,
}]

var beverage = fanta;
var beverage_price = data.prices.beverage;

现在 beverage_price = 10

var beverage = sprite;
var beverage_price = data.prices.beverage;

现在 beverage_price = 20

当我尝试在示例中执行此操作时,脚本会尝试在价格中查找饮料条目。

When I try to do it like in the examples, the script tries to look up the beverage entry in prices.

谢谢很多!!

推荐答案

注释中提到的VisioN data.prices 是一个数组,您需要使用 [0] 其中包含价格 {fanta:10,精灵:20}

As VisioN mentioned in the comment, data.prices is an array, you need to access its first element with [0] which contains prices { "fanta":10, "sprite":20}

这里是工作示例: http://jsfiddle.net/2E8AH/

否则你可以使 data.prices 如下所示的对象:(如果它在你的控制范围内)

Or else you can make data.prices an object like below : (if it is in your control)

var data = {
    "prices" : 
        {
            "fanta":10,
            "sprite":20,
        }
};

并且无需 [0] 即可访问这: http://jsfiddle.net/Y8KtT/1/

and can access without [0] like this : http://jsfiddle.net/Y8KtT/1/

这篇关于JS / Jquery - 在json选择器中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆