We wanna go from:
[{"id":"B390","name":"Peanut butter"},{"id":"B204","name":"Flour"},{"id":"B090","name":"Coconut water"}]
To:
{"B390": "Peanut butter", "B204": "Flour", "B090": "Coconut water"}
Here’s a way in python:
import json
# Here's the string you gave me, just for demonstration
json_string = '[{"id":"B390","name":"Peanut butter"},{"id":"B204","name":"Flour"},{"id":"B090","name":"Coconut water"}]'
# Or this could come from a file:
#
# json_file = "/path/to/file"
# with open(json_file, 'r') as handle:
# json_string = handle.read()
# json.loads (for json load string) will read in a string of json and turn it
# in to stuff python can work with. parsed_json will be entirely python data
# structures -- a list of Dicts
parsed_json = json.loads(json_string)
# Make an empty dict to contain our result
result = {}
for dict in parsed_json:
# For every dict in our list, we'll use the 'id' key's value as the key in
# our result dict
id = dict['id']
result[id] = dict['name']
# Could print the result
print(result)
# Or write it back out to a file We'll use json.dumps (json dump string) to do
# the opposite of loads -- dump python data structures in to a json equivalent
#
# with open('/path/to/a/good/output/file', 'w') as handle:
# stringified_json = json.dumps(result)
# handle.write(stringified_json)