I am retrieving JSON using jQuery's getJSON call.
我正在使用jQuery的getJSON调用检索JSON。
My problem is that some of the fields in the returned JSON have spaces in them.
我的问题是返回的JSON中的一些字段中有空格。
How do I retrieve these values from the JSON without changing the source data? See line marked "ERROR" below:
如何在不更改源数据的情况下从JSON中检索这些值?请参阅下面标有“错误”的行:
$.getJSON(url, null, function(objData) {
$.each(objData.data, function(i, item) {
var zip = item.Zip;
var fname = item.First Name; //ERROR
});
});
Example JSON:
示例JSON:
jsonp123456789({"data":[{"Zip":"12345","First Name":"Bob"},{"Zip":"23456","First Name":"Joe"},{"Zip":"34567","First Name":"Bill"}]})
Thanks
谢谢
2 个解决方案
#1
19
Array member access notation works on objects as well.
数组成员访问表示法也适用于对象。
$.getJSON(url, null, function(objData) {
$.each(objData.data, function(i, item) {
var zip = item.Zip;
var fname = item['First Name'];
});
});
You can use this for arbitrary strings (those that aren't legal identifiers) as well as variables.
您可以将此用于任意字符串(非合法标识符)以及变量。
var fieldName = "First Name";
var fname = item[fieldName];
#2
8
$.getJSON(url, null, function(objData) {
$.each(objData.data, function(i, item) {
var zip = item.Zip;
var fname = item["First Name"]; //Changed this
});
});
reference the item using as a key instead of dot notation
使用键作为键而不是点表示法引用该项
#1
19
Array member access notation works on objects as well.
数组成员访问表示法也适用于对象。
$.getJSON(url, null, function(objData) {
$.each(objData.data, function(i, item) {
var zip = item.Zip;
var fname = item['First Name'];
});
});
You can use this for arbitrary strings (those that aren't legal identifiers) as well as variables.
您可以将此用于任意字符串(非合法标识符)以及变量。
var fieldName = "First Name";
var fname = item[fieldName];
#2
8
$.getJSON(url, null, function(objData) {
$.each(objData.data, function(i, item) {
var zip = item.Zip;
var fname = item["First Name"]; //Changed this
});
});
reference the item using as a key instead of dot notation
使用键作为键而不是点表示法引用该项