我收到了这个小json文件:
{
"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"
}
}
我需要构建一个树,查找“is_a”字段以及此字段前的名称。一旦我得到这两个字段,我就可以将孩子插入树上的正确位置。
所以,使用javascript,如何获取每个名称和字段“is_a”?
我想有一个循环语句,它给我所有的名称和“is_a”字段,例如,它第一次给我“描述”和“AnnotationProperty”,第二次迭代它给了我“相关性”和“ AnnotationProperty“等等。
感谢。
答案 0 :(得分:1)
您可以使用is_a
属性值列出名称,如下所示:
Object.keys(data).forEach(function (name) {
if (data[name].is_a) console.log(name + ' is a ' + data[name].is_a);
});
在一个片段中:
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>'));
答案 1 :(得分:1)
如果您的JSON字符串有效,您可以使用JSON.parse()
函数将其解析为javascript对象。
并且,如果要遍历对象,请使用内置的for in
循环:
var json = {a:1, b:2, c:3};
for (var key in json) {
// key
// json[key] = {is_a: 'xxx', ...}
// json[key][is_a]
}