2

I want to get json from a web page. The json on the page is in the format

[{"ID":"151032",
  "user":"UsersName",
  "message":"This is a message.",
  "date":"1293452007",
  "replies":"1",
  "categories":false,
  "categoriesArray":[],
  "lat":"0.000000000000000",
  "lng":"0.000000000000000"}] 

How can I get user, message, ID and replies from the JSON and display it on another webpage via javascript?

Example: hello UsersName your Id is: 151032 and your message is: This is a message. it has 1 replies.

note: there will be multiple sets of this i.e.

[{"ID":"151032",
  "user":"UsersName1",
  "message":"This is a message.",
  "date":"1293452007",
  "replies":"1",
  "categories":false,
  "categoriesArray":[],
  "lat":"0.000000000000000",
  "lng":"0.000000000000000"},
 {"ID":"151033",
  "user":"UsersName2",
  "message":"This is another message.",
  "date":"1293452007",
  "replies":"2",
  "categories":false,
  "categoriesArray":[],
  "lat":"0.000000000000000",
  "lng":"0.000000000000000"}]

2 Answers 2

4

Use JSON.parse and then access the properties like normal object properties. E.g.

var msgs = JSON.parse(json);

for(var i = 0, l = msgs.length; i < l; i++) {
    var msg = msgs[i];
    var div = document.createElement('div');
    div.innerHTML = 'Hello ' + msg.user + ' your Id is: ' + msg.ID + 'and your message is: ' + msg.message + ' it has ' + msg.replies + ' replies';
    document.body.appendChild(div);
}

Working DEMO

Sign up to request clarification or add additional context in comments.

13 Comments

Ok, thanks for the quick reply. Is it possible to retrieve the JSON from a webpage for example stackoverflow.com/jsonstuff.json
@user556396 generally you would retrieve the JSON with AJAX requests.
@AJ00200: The JSON object is available in most browsers now afaik. If not, one can always use json.org/js.html
@AJ00200 Would that work even if the JSON is on a different server?
@user556396: Then you'd need to use JSONP: en.wikipedia.org/wiki/JSONP, to circumvent the same-origin policy (but the server has to support it, if not, no chance).
|
0

Although it is not safe, you can eval() the JSON data (but this could be a security issue for your users, so it would be best to use a parsing library). After eval()ing it, you can access the data like data[0]["ID"]

You can get a JSON parser here: http://www.json.org/js.html

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.