4

How can I access this data?

Here is my Json:

 {
  "6a768d67-82fb-4dd9-9433-d83dbd2f1b78": {
    "name": "Bahut",
    "11": {
      "timestamp": 1380044486000,
      "value": "false"
    }
  },
  "4f4a65e4-c41b-4038-8f62-76fe69fedf60": {
    "name": "Vit",
    "11": {
      "timestamp": 1380109392000,
      "value": "false"
    }
  },
  "a12d22cc-240e-44d6-bc58-fe17dbb2711c": {
    "name": "Cuis",
    "11": {
      "timestamp": 1379883923000,
      "value": "false"
    }
  }
}

I'm trying to read and extract for each entries the id (xxxxxxxx-xxxx-...-xxxxxxxxx) and the "name" to put then in an array.

But I didn't manage to do.

trying :

var nameid = json.'XXXXX-....-XXXX'.name;

or replace '-' by ''

var nameid = json.XXXXXXXXX.name;

didn't work too.

5 Answers 5

7

You need to use array-style access to get the subobject associated with the id key:

var nameid = json["a12d22cc-240e-44d6-bc58-fe17dbb2711c"].name; // or ["name"]
// nameid => "Cuis"

This is because hyphens are not a valid character for dot-style access (can't use them in variable names in JavaScript).

In order to extract all of the you will need to loop through the object, and add them to an array, like so:

var arr = [];
for (var id in json) {
    arr.push(json[id]["name"]);
}

Which will give you an array of all the names in that JSON object.

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

2 Comments

For the extraction, the result of array give me : 0 undefined 1 undefined 2 undefined
Using your exact JSON object and my exact code, copy-pasted, I get ["Bahut", "Vit", "Cuis"] in arr.
1

You could use Object.keys to get an array of properties.

var js = JSON.parse(json);
var props = Object.keys(js);

var result = props.map(function(prop) {
  return {
    id: prop,
    name: js[prop].name;
  };
});

The final result is an array of objects with 2 properties: id, name

Comments

1

If you want to loop through the data, use a for in loop:

for (var key in obj) { //obj is your data variable
    console.log(key); //xxxx-x-xx-x-x-xxxx
    console.log(obj[key].name); //the name for each
}

Comments

0

Access the JSON like you would an array, eg:

data["a12d22cc-240e-44d6-bc58-fe17dbb2711c"].name

jsfiddle

Comments

0

not a common way of looping, but in this case you could loop over the json object

for (var prop in json){
     print("prop",json[prop].name);
}

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.