12

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

4
  • Why is there a space in the JSON name if you want to use it as a Javascript Object? Commented Dec 8, 2009 at 0:05
  • Spaces are allowed in identifiers, awkward but allowed. Commented Dec 8, 2009 at 0:45
  • I know you can do it. The question is why not just use FirstName so you can use the nice clean dot syntax. Commented Dec 8, 2009 at 1:04
  • In my case, the JSON data is provided by a 3rd party. If I controlled the data, I would probably use FirstName. Commented Dec 8, 2009 at 1:11

2 Answers 2

22

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];
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.