JsonPath:如何为每个孩子提取父母?

时间:2016-05-03 16:52:32

标签: json geojson jsonpath

有了这个json:

{"ROOT": {"PARENT": {
    "parentName": "Joe",
    "children": {"child": [
        "Mike",
        "Bob",
        "Nick"
    ]}
}}}

我想为每个孩子提取父母,即使是相同的。 如果我使用这个:

$.ROOT.PARENT[?(@.children.child)].parentName

我会:

'0' => "Joe"

但我想要像:

'0' => "Joe" //Mike's father name
'1' => "Joe" //Bob's father name
'2' => "Joe" //Nick's father name

任何想法我怎么能为此创建一个json expresison?

1 个答案:

答案 0 :(得分:0)

不假设这需要递归

var data, 
    parent,
    childArr,
    i

data = {
	"ROOT": {
		"PARENT": {
			"parentName": "Joe",
			"children": {
				"child": ["Mike","Bob","Nick"]
			}
		}
	}
}

parent = data.ROOT.PARENT.parentName,
childArr = data.ROOT.PARENT.children.child
for(i = 0; i < childArr.length; i++){
  child = childArr[i]
  console.log('child', child, 'parent', parent)
  document.body.innerHTML += 'child ' + child + ' parent ' + parent + '</br>'
}