简体   繁体   English

Python 从 JSON 读取逗号分隔列表

[英]Python reading comma seperated list from JSON

I have the following JSON structure given in a python script:我在 python 脚本中给出了以下 JSON 结构:

print("Producers: ", metadata['plist']['dict']['array'][2]['dict']['string'])

The Problem is that I don't have a single entry on that field, instead I have multiple ones.问题是我在该字段上没有一个条目,而是有多个条目。 Please also see the RAW JSON here: https://pastebin.com/rtTgmwvn另请参阅此处的原始 JSON: https://pastebin.com/rtTgmwvn

How can I pull out these entries as a comma separated string for [2] which is the producers field?如何将这些条目作为逗号分隔的字符串提取到 [2] 的生产者字段中?

Thanks in advance提前致谢

You're almost there:您快到了:

you can do something like this你可以做这样的事情

print("Producers: ", ", ".join(i["string"] for i in metadata['plist']['dict']['array'][2]['dict'])

to break down the solution... your "dict" element in the JSON is actually a list of " dict ", and therefore you can simply iterate over this list :分解解决方案... JSON 中的"dict"元素实际上是“ dictlist ,因此您可以简单地遍历此list

metadata['plist']['dict']['array'][2]['dict']

where each element is an actual dict with a "string" key.其中每个元素都是带有"string"键的实际dict

Update更新

The format of the JSON is so tahat in some cases it is a list, and in some cases it is a single element. JSON 的格式在某些情况下是一个列表,在某些情况下是单个元素。 In that case, I would suggest writing a small function or use an if statement that handles each situation:在这种情况下,我建议编写一个小的 function 或使用处理每种情况的if语句:

def get_csv(element):
    if isinstance(element, dict):
        return element["string"]
    return ", ".join(i["string"] for i in element)

# and you would use it like so:
print("Producers: ", get_csv(metadata['plist']['dict']['array'][2]['dict']))

The following should do the trick:以下应该可以解决问题:

def get_producer_csv(data):
    producers = []
    dict = data["plist"]["dict"]["array"][2]["dict"]
    for dict_entry in dict:
        producers.append(dict_entry["string"])
    return ",".join(producers)

For your example, it returns the following: "David Heyman,David Barron,Tim Lewis"对于您的示例,它返回以下内容:“David Heyman,David Barron,Tim Lewis”

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

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