How to extract a key value from json file (python)

Question:

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?

Asked By: Miteals 71

||

Answers:

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.

Answered By: Vadim Beskrovnov

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...",
]
Answered By: Andrej Kesely

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
Answered By: Seasers
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.