簡體   English   中英

從 Json 返回特定路徑 python 的值

[英]Return values from a Json for a specific path python

我有這個 Json 作為字符串:

json_String= {
    "type": [
        {
            "color": "blue",
            "contrast": "high",
            "stock": "enough"
        },
        {
            "color": "orange",
            "contrast": "high",
            "stock": "enough",
            "details": "noneTobeGiven"
        },
        {
            "color": "red",
            "contrast": "low",
            "stock": "enough",
            "details": "noneTobeGiven"
        },
        {
            "color": "blue",
            "contrast": "high",
            "stock": "enough",
            "details": "noneTobeGiven"
        }
    ]
}

從中創建一個字典:

dict1 = eval(json_String)

基於這個答案,我試圖返回特定路徑的標簽的所有出現

from functools import reduce  # forward compatibility for Python 3
import operator

def get_by_path(root, items):
    """Access a nested object in root by item sequence."""
    return reduce(operator.getitem, items, root)


print(get_by_path(dict1, ["type", "color"]))

但是收到一個錯誤:

TypeError: list indices must be integers or slices, not str

我認為這是因為列表,它需要一個索引而不是 str,並試圖這樣調用模塊:

print(get_by_path(dict1, ["type", "color"][0]))

結果是:

    return reduce(operator.getitem, items, root)

鍵錯誤:'t'

目標

對於給定的路徑,假設 type.color,為每次出現返回 [color] 的所有值:

print(get_values_by_path("type.color")

[“藍色”、“橙色”、“紅色”、“藍色”]

from jsonpath_ng import jsonpath, parse
import json


json_data = json.loads(Json string from the description above)


print(json_data)

jsonpath_expression = parse('type[*].color')

for match in jsonpath_expression.find(json_data):
    print(f' Color: {match.value}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM