javascript 如何使用 jquery 从 json 对象中获取值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34136552/
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
How to get value from json object using jquery?
提问by adam78
I have the following ajax call and the json feed it returns. how do I get the value of the data object i.e. FRI from the feed using jquery?
我有以下 ajax 调用和它返回的 json 提要。如何使用 jquery 从提要中获取数据对象的值,即 FRI?
$.ajax({
url: query,
type: "GET",
dataType: "json"
success: function(data) {
var day = // get data value from json
$("#Day").val(day);
}
});
{
"name":"workdays",
"columns":[
"day"
],
"data":[
[
"FRI"
]
]
}
* update *
* 更新 *
What would be the syntax be if the results were returned as jsonp as follows, how can you extract the value 'FRI' :
如果结果作为 jsonp 返回如下,语法是什么,如何提取值 'FRI' :
import({
"Results":{
"work_days":{
"empid":100010918994,
"day":"FRI"
}
}
});
采纳答案by Arg0n
This is just JavaScript, not jQuery.
这只是 JavaScript,而不是 jQuery。
var data = {
"name":"workdays",
"columns":[
"day"
],
"data":[
[
"FRI"
]
]
}
data.data[0][0]; //FRI
UPDATE
更新
var obj = {
"Results":{
"work_days":{
"empid":100010918994,
"day":"FRI"
}
}
}
obj.Results.work_days.day //FRI
回答by Ronny Coolen
If the latter json is the json you get from the server, you can get the data like this:
如果后面的json是你从服务器获取的json,你可以这样获取数据:
var day = data.data[0][0];
This will put the value FRI
in the variable day
.
这会将值FRI
放入变量中day
。
EDIT:If you use a recent browser, you can always do console.log(data)
and look in your javascript console what is in the variable
编辑:如果您使用最近的浏览器,您可以随时console.log(data)
查看您的 javascript 控制台中的变量
回答by Jay
$.ajax({
url: query,
type: "GET",
dataType: "json"
success: function(data) {
var day = data.data[0][0] // get data value from json
$("#Day").val(day);
}
});
{
"name":"workdays",
"columns":[
"day"
],
"data":[
[
"FRI"
]
]
}
回答by Omar Mowafi
You don't need jquery data is a javascript object (hash). You can access the data as follow:
你不需要 jquery 数据是一个 javascript 对象(哈希)。您可以按如下方式访问数据:
data.columns
Or
或者
data["columns"]
回答by michal pavlik
json is javascript object, so you can access to any his property:
json 是 javascript 对象,因此您可以访问他的任何属性:
data.name
data.columns
data.data
回答by Dragos
For retrieving the 'data' field
用于检索“数据”字段
$.ajax({
url: query,
type: "GET",
dataType: "json"
success: function(data) {
var day = data['data']; // get data value from json
$("#Day").val(day);
}
});
{
"name":"workdays",
"columns":[
"day"
],
"data":[
[
"FRI"
]
]
}
回答by CGalvao
Have you ever checked the data.d variable?
你有没有检查过 data.d 变量?
success: function(data) {
console.log(data.d); //prints the value
}