I have a json object:
{
"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"}]},
]
}
and I want to get the list of detail of each person
[
["hello", "world"],
["andy"],
["dave"],
]
I am wondering if this is even possible? I have tried many things but the array got flatten out and that is not ideal.
The json you provide isn't valid (so I added a name of the array):
{
"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"}]},
]
}
To get all details here:
$..detail
the result of it is:
[
"hello",
"world",
"andy",
"dave"
]
tested with http://jsonpath.curiousconcept.com/ (Jsonpath 0.8.3)
Okay, I'm guessing your JSON should be an array of objects and not an object containing an array. If so, then this is how you could do it;
$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));
This would then give you the values in the structure you want;
[
['hello', 'world'],
['andy'],
['dave']
]
The sample JSON has one excess comma. Assuming it has been removed, the following invocation:
jq -cf '[.context[] | [.node[] | .detail]]' input.json
produces:
[["hello","world"],["andy"],["dave"]]
http://stedolan.github.io/jq is very similar to JSONpath. See "jq for JSONpath users" .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.