我有一个json对象:
{
"context": [
{"name": "John", "node": [{"id": 1, "detail": "hello"}, {"id": 2, "detail": "world"}]},
{"name": "Andy", "node": [{"id": 3, "detail": "andy"}]},
{"name": "Dave", "node": [{"id": 4, "detail": "dave"}]},
]
}
我希望获得每个人的详细信息列表
[
["hello", "world"],
["andy"],
["dave"],
]
我想知道这是否可能?我尝试了很多东西,但阵列变得扁平,这并不理想。
答案 0 :(得分:0)
您提供的json无效(所以我添加了数组的名称):
{
"persons": [
{"name": "John", "node": [{"id": 1, "detail": "hello"}, {"id": 2, "detail": "world"}]},
{"name": "Andy", "node": [{"id": 3, "detail": "andy"}]},
{"name": "Dave", "node": [{"id": 4, "detail": "dave"}]},
]
}
要在此处获取所有详细信息:
$..detail
结果是:
[
"hello",
"world",
"andy",
"dave"
]
用http://jsonpath.curiousconcept.com/(Jsonpath 0.8.3)测试
答案 1 :(得分:0)
好的,我猜你的JSON应该是一个对象数组,而不是一个包含数组的对象。如果是这样,那么你就是这样做的;
$json = <<<EOF
[
{"name": "John", "node": [{"id": 1, "detail": "hello"},{"id": 2, "detail": "world"}]},
{"name": "Andy", "node": [{"id": 3, "detail": "andy"}]},
{"name": "Dave", "node": [{"id": 4, "detail": "dave"}]}
]
EOF;
$map = array_map(function($object) {
return array_map(function($detail) {
return $detail->detail;
}, $object->node);
}, json_decode($json));
然后,这将为您提供所需结构中的值;
[
['hello', 'world'],
['andy'],
['dave']
]
答案 2 :(得分:0)
示例JSON有一个多余的逗号。假设它已被删除,则进行以下调用:
jq -cf '[.context[] | [.node[] | .detail]]' input.json
产生
[["hello","world"],["andy"],["dave"]]
http://stedolan.github.io/jq与JSONpath非常相似。请参阅"jq for JSONpath users"。