How to return the name of an existing object in a JSON

3

I have the JSON file below:

{
  "uid1":{
    "start_time":"20140815",
    "name":"name 1"
    },
  "uid2":{
    "start_time":"20141229",
    "name":"name 2"
    },
  "uid3":{
    "start_time":"20140809",
    "name":"name 3"
    },
  "uid4":{
    "start_time":"20140830",
    "name":"name 4"
    },
  "uid5":{
    "start_time":"20140920",
    "name":"name 5"
    }
}

I need not only return the values within each " uid " but also the " uid " name of the uid something like this:

uid1,20140815,name 1
    
asked by anonymous 17.07.2014 / 18:44

2 answers

2

You can do something like this:

var obj = {
    "uid1": {
        "start_time": "20140815",
            "name": "name 1"
    },
        "uid2": {
        "start_time": "20141229",
            "name": "name 2"
    },
        "uid3": {
        "start_time": "20140809",
            "name": "name 3"
    },
        "uid4": {
        "start_time": "20140830",
            "name": "name 4"
    },
        "uid5": {
        "start_time": "20140920",
            "name": "name 5"
    }
};

// Montagem dos resultados.

var resultado = [];

for (var prop in obj) {
    resultado.push(prop + ',' + obj[prop].start_time + ',' + obj[prop].name);
}

// Exibição dos resultados.

for (var i = 0; i < resultado.length; i++) {
    alert(resultado[i]);
}
    
17.07.2014 / 19:16
1

You can do it this way

JQuery

var json = {
  "uid1":{
    "start_time":"20140815",
    "name":"name 1"
    },
  "uid2":{
    "start_time":"20141229",
    "name":"name 2"
    },
  "uid3":{
    "start_time":"20140809",
    "name":"name 3"
    },
  "uid4":{
    "start_time":"20140830",
    "name":"name 4"
    },
  "uid5":{
    "start_time":"20140920",
    "name":"name 5"
    }
};

$(function(){
    $.each(json, function(i, v){
       $('ul').append('<li>'+ i + ', ' + v.start_time + ', ' + v.name +'</li>'); 
    });
});

The above example populates a <ul> element, use it to adapt your application.

You can also view this DEMO with the working example

    
17.07.2014 / 19:19