I'm trying to write a program that extracts all labels from a given JSON file:
{"menu": {
"header": "SVG Viewer",
"items": [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},
null,
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "OriginalView", "label": "Original View"},
null,
{"id": "Quality"},
{"id": "Pause"},
{"id": "Mute"},
null,
{"id": "Find", "label": "Find..."},
{"id": "FindAgain", "label": "Find Again"},
{"id": "Copy"},
{"id": "CopyAgain", "label": "Copy Again"},
{"id": "CopySVG", "label": "Copy SVG"},
{"id": "ViewSVG", "label": "View SVG"},
{"id": "ViewSource", "label": "View Source"},
{"id": "SaveAs", "label": "Save As"},
null,
{"id": "Help"},
{"id": "About", "label": "About Adobe CVG Viewer..."}
]
}}
Actually I'm completely novice and dunno how to get over this.
And is there a way to do such a thing in bash?
Solution in Python:
import json
with open("your_file.json", "r") as f_in:
data = json.load(f_in)
all_labels = [i["label"] for i in data["menu"]["items"] if i and "label" in i]
print(all_labels)
Prints:
[
"Open New",
"Zoom In",
"Zoom Out",
"Original View",
"Find...",
"Find Again",
"Copy Again",
"Copy SVG",
"View SVG",
"View Source",
"Save As",
"About Adobe CVG Viewer...",
]
Try to follow this manual for python: https://www.w3schools.com/python/python_json.asp
For bash, you can use jq
: https://stedolan.github.io/jq/
If you face any issues, feel free to ask specific questions.
Bash Solution
Install jq: https://stedolan.github.io/jq/download/
Command:
jq '.[].items[].label // "-"' path/to/your/json/file.json
Output:
"Open New"
"Zoom In"
"Zoom Out"
"Original View"
"Find..."
"Find Again"
"Copy Again"
"Copy SVG"
"View SVG"
"View Source"
"Save As"
"About Adobe CVG Viewer..."
To remove double quotes, add -r
:
jq -r '.[].items[].label // "-"' path/to/your/json/file.json
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.