The correct way to parse a JSON file is to use a JSON parser. The jq
utility is one such parser that is made for use on the command line and in scripts:
jq -r '.properites.apps[]' apps.json
This would output
apple
orange
mango
This asks jq
to extract the elements of the array apps
in the top-level object properites
in the JSON document in the file apps.json
.
The -r
option asks jq
to output "raw" data rather than JSON-encoded data.
To get tab-delimited output on a single line, use
jq -r '.properites.apps | @tsv' file
This would output
apple orange mango
The @tsv
operator takes an array and outputs it as a tab-delimited list. You could instead use @csv
to get properly quoted CSV output.
Note that this would also work no matter whether your JSON document was
{
"properites": {
"apps": [
"apple",
"orange",
"mango"
]
}
}
or
{"properites":{"apps":["apple","orange","mango"]}}
(these are equivalent forms of the same JSON document).
jq
. Everything else is just a recipe for headaches. – Panki Feb 12 at 9:48jq -r '.properites.apps[]' apps.json
(using the misspelling from the example) – Uncle Billy Feb 12 at 9:54[]
at the end of thejq
expression. You want each individual element of the list, not the list as a whole. – Kusalananda♦ Feb 12 at 10:37