简体   繁体   English

从 Json 返回特定路径 python 的值

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

I have this Json as string:我有这个 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"
        }
    ]
}

creating a dict from it:从中创建一个字典:

dict1 = eval(json_String)

Based on this answer I'm tring to return all the occurances of a tag for a specific path基于这个答案,我试图返回特定路径的标签的所有出现

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"]))

But an error is received:但是收到一个错误:

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

I assume this is because of the list and it expects an index instead of str, and tried to call the module as such:我认为这是因为列表,它需要一个索引而不是 str,并试图这样调用模块:

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

The result was:结果是:

    return reduce(operator.getitem, items, root)

KeyError: 't'键错误:'t'

Goal目标

For a given path, lets say type.color, to return all the values for [color] for every occurance:对于给定的路径,假设 type.color,为每次出现返回 [color] 的所有值:

print(get_values_by_path("type.color")

["blue", "orange", "red", "blue"] [“蓝色”、“橙色”、“红色”、“蓝色”]

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