使用 javascript 从 JSON 获取特定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18306675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting specific value from JSON using javascript
提问by RavenXV
I am using ajax to get a small set of data back from the server which returns JSON data with the following format:
我正在使用 ajax 从服务器获取一小组数据,该数据返回具有以下格式的 JSON 数据:
{
"data": [
{
"id": "1",
"value": "One"
},
{
"id": "2",
"value": "Two"
},
{
"id": "3",
"value": "Three"
}
]
}
On the client side, this is assigned to a variable named response
. I use response.data
to get the contents.
在客户端,这被分配给一个名为 的变量response
。我response.data
用来获取内容。
The question is, is there an easier way to get the value without doing a loop?
I'm kinda looking for something like this response[id==2].value
which should give me "Two".
问题是,有没有更简单的方法来获取值而不进行循环?我有点在寻找这样的东西response[id==2].value
,它应该给我“两个”。
I'm open for any suggestions if this is not possible.
如果这是不可能的,我愿意接受任何建议。
采纳答案by dwerner
You could take a functional approach and use the Array.filtermethod:
您可以采用函数式方法并使用Array.filter方法:
var matchingResults = JSON['data'].filter(function(x){ return x.id == 2; });
// procede to use matching elements...
回答by CorayThan
If you parse it into a javascript object using something like jQuery's json parse method, you could just reference the various items in the array like a normal javascript array.
如果您使用类似 jQuery 的json parse 方法将其解析为 javascript 对象,则您可以像普通的 javascript 数组一样引用数组中的各种项目。
Do it like this:
像这样做:
var dataArray = $.parseJSON(myJson).data;
var theFirstData = dataArray[0]; //get the data with id "1"
Alternately, if you don't want to use jQuery, you can use JSON.parse(jsonToParse)
. Here're the docs for that method.
或者,如果您不想使用 jQuery,则可以使用JSON.parse(jsonToParse)
. 这是该方法的文档。