I got this little json file:
{
"description": {
"is_a": "AnnotationProperty",
"labelEN": "description",
"labelPT": "descrição"
},
"relevance": {
"is_a": "AnnotationProperty",
"domain": "Indicator",
"labelEN": "relevance",
"labelPT": "relevância"
},
"title": {
"is_a": "AnnotationProperty",
"labelPT": "título",
"labelEN": "title",
"range": "Literal"
}
}
I need to build a tree looking for the "is_a" field and the name before this field. Once I got these two fields, I can insert the child one on the tree in the right place.
So, using javascript, how can I get the name and the field "is_a" of each one?
I would like to have a loop statement that gives me all the names and "is_a" fields, for example, first time it gives me "description" and "AnnotationProperty" and the second iteration it gives me "relevance" and "AnnotationProperty", etc.
Thanks.
-
It is not json, it's yaml file!Uzbekjon– Uzbekjon2016年05月01日 20:04:31 +00:00Commented May 1, 2016 at 20:04
-
I'm so sorry. I put the wrong one. Editing...Pedro Henrique Calixto– Pedro Henrique Calixto2016年05月01日 20:05:38 +00:00Commented May 1, 2016 at 20:05
-
1Please give a sample output you are expecting.trincot– trincot2016年05月01日 20:10:35 +00:00Commented May 1, 2016 at 20:10
-
Sorry again. Edited.Pedro Henrique Calixto– Pedro Henrique Calixto2016年05月01日 20:16:25 +00:00Commented May 1, 2016 at 20:16
-
Did it, trincot. Thanks.Pedro Henrique Calixto– Pedro Henrique Calixto2016年05月01日 20:22:48 +00:00Commented May 1, 2016 at 20:22
2 Answers 2
You can list the names with their is_a property values like this:
Object.keys(data).forEach(function (name) {
if (data[name].is_a) console.log(name + ' is a ' + data[name].is_a);
});
In a snippet:
var data = {
"description": {
"is_a": "AnnotationProperty",
"labelEN": "description",
"labelPT": "descrição"
},
"relevance": {
"is_a": "AnnotationProperty",
"domain": "Indicator",
"labelEN": "relevance",
"labelPT": "relevância"
},
"title": {
"is_a": "AnnotationProperty",
"labelPT": "título",
"labelEN": "title",
"range": "Literal"
}
};
// collect name & is_a
result = [];
Object.keys(data).forEach(function (name) {
if (data[name].is_a) result.push(name + ' is a ' + data[name].is_a);
});
// output in snippet
document.write(result.join('<br>'));
4 Comments
If your JSON string was valid, you could have parsed it into javascript object using JSON.parse() function.
And, if you want to iterate through an object, use built-in for in loop:
var json = {a:1, b:2, c:3};
for (var key in json) {
// key
// json[key] = {is_a: 'xxx', ...}
// json[key][is_a]
}