0

I have a very basic JSON extract seen here.

[
  { first: "bob", last: "jones", },
  { first: "josh", last: "smith", }
]

I am trying to parse this into HTML using $.getJSON.

I have never used this jquery function before and am having issues. My guess is I am missing something in the info div.

I currently have JSON URL in this example but my live code has the actual URL.

Thanks for any guidance, here is my code:

Javascript

$.getJSON('JSON URL', 'limit=5', processNames);

function processNames(data) {
  var infoHTML='';

  $.each(data, function(name) {
    infoHTML += 'First: ' + name.first;
    infoHTML += 'Last: ' + name.last;
  });

  $('#info').html(infoHTML);
}

HTML

<div id="info"></div>
1
  • 1
    Note: The browser has a security feature called same-origin-policy, and can prevent you from receiving a response if the URL names a different port or server. I can't tell if this is an issue but is worth thinking about. Commented Aug 12, 2013 at 7:06

2 Answers 2

3

Your JSON is invalid. You are missing quotes around the field names. Try something like this:

[
    { "first": "Bob", "last": "Jones" },
    { "first": "Josh", "last": "Smith" }
]
Sign up to request clarification or add additional context in comments.

2 Comments

is there a way to alter how a resulting json is formatted? this is a rails based app. thanks.
@brad I have little experience with Rails but I imagine there's definitely a way to get it formatted correctly. Maybe search the docs.
0

In JSON, keys must be in double quotes (so must strings). Single quotes aren't allowed, and quotes are required.

When using JSON you must make sure that it is a valid one.

it is very easy to miss a comma,quote or mismatch brackets. for that purpose I recommend using JSON validator

When checking the JSON object in your question I found that it's invalid for two reasons:

  1. A valid JSON object must always wrap the property name with ["]
  2. There is an extra comma [,] right after the second value while there should be curly brackets instead.

When getting an answer from the server I recomend to check and see if this is the answer you expected it to be. for example, before $.each(data, function(name) you can do the following

alert(JSON.stringify(data,));

This will show you the string received from the server.

Generally I recomend using $.ajax instead of $.getJSON because you have more control over the response from the server, you can decide if you want it cached, asynchronous call and so on.

you can see the jQuery Ajax API here

Hoped my answer helped you.

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.