Jump to content

extending json


dweb

Recommended Posts

Hi

 

I wonder f you can help as i've been racking my brain all night and cannot find a solution

 

I have the following JSON in a file

 

{
            "user1": 'David',
            "user2": 'Julie',
            "user3": 'John'
}

 

and I output it with

 

$.getJSON("files/json.txt", function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li>' + key + '<br>' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo("#"+divname);
});

 

all works fine, but I need to extend the JSON so that it looks like the following

 

{
            "id": "14373",
            "name": 'David',
            "age": '25',
            "gender": 'm',
            "id": "14373",
            "name": 'Julie',
            "age": '31',
            "gender": 'f',
            "id": "65643",
            "name": 'John',
            "age": '42',
            "gender": 'm'
}

 

and then output it as something like;

 

  $.each(data, function(id_val, name_val, age_val, gender_val) {
    items.push('<li>' + id_val + '<br>' + name_val + '<br>' + age_val + '<br>' + gender_val + '</li>');
  });

 

is this possible and if so, how can it be done as im really struggling to find a way

 

thanks everyone

Link to comment
Share on other sites

Can't reuse keys like that. You need an outer array along the lines of

[{
"id": 14373,
"name": "David",
"age": 25,
"gender": "m"
}, {
"id": 14373,
"name": "Julie",
"age": 31,
"gender": "f"
}, {
"id": 65643,
"name": "John",
"age": 42,
"gender": "m"
}]

With that done, start using each() properly.

Link to comment
Share on other sites

thanks, i've read the page but could you give me a simple example of how to extract and display it? i've looked around and finding it hard to find something straight forward and now banging my head against the wall

 

 

thanks

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.