简体   繁体   English

如何从 json 文件中提取键值(python)

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

I'm trying to write a program that extracts all labels from a given JSON file:我正在尝试编写一个程序,从给定的 JSON 文件中提取所有标签:

{"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?有没有办法在 bash 中做这样的事情?

Solution in Python: 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尝试按照本手册了解 python: https://www.w3schools.com/python/python_json.asp

For bash, you can use jq : https://stedolan.github.io/jq/对于 bash,您可以使用jqhttps://stedolan.github.io/jq/

If you face any issues, feel free to ask specific questions.如果您遇到任何问题,请随时提出具体问题。

Bash Solution Bash 解决方案

Install jq: https://stedolan.github.io/jq/download/安装jq: https://stedolan.github.io/jq/download/

Command:命令:

jq '.[].items[].label // "-"' path/to/your/json/file.json

Output: 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 :要删除双引号,请添加-r

jq -r '.[].items[].label // "-"' path/to/your/json/file.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM