-1

I have the following JSON structure given in a python script:

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

How can I pull out these entries as a comma separated string for [2] which is the producers field?

Thanks in advance

  • Does this answer your question? [Getting a list of values from a list of dicts](https://stackoverflow.com/questions/7271482/getting-a-list-of-values-from-a-list-of-dicts) – 0stone0 May 28 '21 at 17:32
  • @0stone0 almost, I need to know how I can make it work if the field sometimes has multiple entries and sometimes not, please see my comment in the answer –  May 28 '21 at 17:38

2 Answers2

0

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:

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

where each element is an actual dict with a "string" key.

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. In that case, I would suggest writing a small function or use an if statement that handles each situation:

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']))
Mateo Torres
  • 1,545
  • 1
  • 13
  • 22
  • @ Mateo Torres a question beside, how can I make this work if the given Dataset has just one entry, please see JSON ecample again, directors for example is just on entry and does not work :( Sometime these fields have multiple entries, sometimes not –  May 28 '21 at 17:36
0

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"

maweil
  • 91
  • 4