How can i get values from json and display them in javascript

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"}]

Answers:

Answer

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

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.