dtc348
dtc348

Reputation: 364

copy json objects and add to main json object, if keys has more than one value

I am having JSON data, where some key has more than one value. I want to make a copy of json body and add it to main json.

For example, in my given.json, number has two values 156 and 158 and respectively. I want to make copy and add of it, please see my expected.json result.

given.json

[{"fields": {"Start": "yes1",
   "number": [156, 158],
   "time": 1600,
   "total": 8}}]

expected.json

[{"fields": {"Start": "yes1",
   "number": [156],
   "time": 1600,
   "total": 8}},
 {"fields": {"Start": "yes1",
   "number": [158],
   "time": 1600,
   "total": 8}}]

python

import json

# Opening JSON file
f = open('given.json',)

# returns JSON object as
# a dictionary
main_data = json.load(f)

my_dict = []

main_data[0]["fields"]["number"] = 156
main_data_1 = []
main_data_1.append(main_data)
my_dict.append(main_data_1)

main_data[0]["fields"]["number"] = 158
main_data_2 = []
main_data_2.append(main_data)

my_dict.append(main_data_2)

print(my_dict)

Upvotes: 0

Views: 2919

Answers (1)

martineau
martineau

Reputation: 123483

You seem to be confused between dictionaries and lists. json.load() can return either and in this case it will be a list (with only one element in it, which is a dictionary).

In the code below, a second element which is a copy of the first made, and then each element is modified according. The copy is a "deep copy" so the values in the dictionary copies are all independent.

from copy import deepcopy
import json
from pprint import pprint

with open('given.json') as f:
    main_data = json.load(f)

numbers = main_data[0]["fields"]["number"]
main_data = [deepcopy(main_data[0]) for _ in numbers]

for i, number in enumerate(numbers):
    main_data[i]["fields"]["number"] = [number]

pprint(main_data, sort_dicts=False)

Output:

[{'fields': {'Start': 'yes1', 'number': [156], 'time': 1600, 'total': 8}},
 {'fields': {'Start': 'yes1', 'number': [158], 'time': 1600, 'total': 8}}]

Upvotes: 1

Related Questions