簡體   English   中英

如何從 json 文件中提取鍵值(python)

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

我正在嘗試編寫一個程序,從給定的 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..."}
    ]
}}

實際上,我完全是新手,不知道如何克服這一點。

有沒有辦法在 bash 中做這樣的事情?

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)

印刷:

[
    "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...",
]

嘗試按照本手冊了解 python: https://www.w3schools.com/python/python_json.asp

對於 bash,您可以使用jqhttps://stedolan.github.io/jq/

如果您遇到任何問題,請隨時提出具體問題。

Bash 解決方案

安裝jq: https://stedolan.github.io/jq/download/

命令:

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..."

要刪除雙引號,請添加-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