March 7, 2013

How do I get specific parts of JSON files for use with HTML?

Question by user2137541

I would like to import JSON data from a file, the code I have at the moment is:

    $.getJSON('data.json', function(data) {             
    var output = "<tr>";
    for ( var i in data.users) {
    output += "<td>"
    + "-- "
    + data.users[i].time
    + " --<br>-- "
    + data.users[i].senderID
    + " --<br>"
    + data.users[i].message
    + "<br></br></td>";
    output += "</tr>";
    document.getElementById("placeholder").innerHTML = output;

But I can no longer access it as it doesnt get generated with a nice neat name like “users” as you can see below it is “¬í t’” but you cant reference to that as part of it isnt valid characters

    ¬í t’{  
    "messageId": 53,  
    "userTo": {    
    "userId": 4,    
    "userName": "Bob123",    
    "userLastCheckedDate": "Mar 7, 2013 11:14:53 AM"

    "userFrom": {
    "userId": 1,
    "userName": "Joe123",    
    "userLastCheckedDate": "Mar 7, 2013 10:41:44 AM"

    "messageContent": "a lovely message here",
    "messageSentDate": "Mar 7, 2013 11:36:14 AM",
    "messageReadDate": "Mar 7, 2013 12:49:52 PM"

Any ideas? Thanks!

Also, this is the java that generates the JSON

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(userMessages.get(0));

Answer by Starx

You can access the object as array too.

for ( var i in data['’ t'']) {



Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!