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?
CodePudding user response:
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...",
]
CodePudding user response:
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.