当前位置: 动力学知识库 > 问答 > 编程问答 >

In JavaScript/jQuery, how to retrieve data that has spaces in its name?

问题描述:

I am retrieving JSON using jQuery's getJSON call.

My problem is that some of the fields in the returned JSON have spaces in them.

How do I retrieve these values from the JSON without changing the source data? See line marked "ERROR" below:

$.getJSON(url, null, function(objData) {

$.each(objData.data, function(i, item) {

var zip = item.Zip;

var fname = item.First Name; //ERROR

});

});

Example JSON:

jsonp123456789({"data":[{"Zip":"12345","First Name":"Bob"},{"Zip":"23456","First Name":"Joe"},{"Zip":"34567","First Name":"Bill"}]})

Thanks

网友答案:

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];
网友答案:
$.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

分享给朋友:
您可能感兴趣的文章:
随机阅读: