0

I am new to JSON, never used python packages to manipulate JSON files. I have 10 JSON files that I would like to merge into one using python.

Each of 10 files has the exact same structure and has about 50,000 entries

Example:

File one

{"tracking_code":"21703238","from_country":"FR","to_country":"FR","amount":3.23}
...

Example: File two

{"tracking_code":"41545695","from_country":"FR","to_country":"FR","amount":2.9}
...

Desired output would simply be:

{"tracking_code":"21703238","from_country":"FR","to_country":"FR","amount":3.23}
{"tracking_code":"41545695","from_country":"FR","to_country":"FR","amount":2.9}

The second part of my questions would be this - how would I join JSON files based on one key? I would like to join these 2 files by "tracking_code", the output file would simply add '"amount":3.23' to the first file.

Example: File one:

{"tracking_code":"29285908","from_country":"FR","to_country":"FR",
"package_type_id":10,"transaction_id":172238850,
"shipping_label_created":"2018-09-25 18:40:52"}

Example: File two

{"tracking_code":"29285908","from_country":"FR","to_country":"FR","amount":3.23}

Desired output:

{"tracking_code":"29285908","from_country":"FR","to_country":"FR",
"package_type_id":10,"transaction_id":172238850,
"shipping_label_created":"2018-09-25 18:40:52","amount":3.23}

Thank you.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jonas Palačionis
  • 4,591
  • 4
  • 22
  • 55
  • 1
    Possible duplicate of [Issue with merging multiple JSON files in Python](https://stackoverflow.com/questions/23520542/issue-with-merging-multiple-json-files-in-python) – shaik moeed Oct 17 '19 at 09:01

1 Answers1

0

If you use json.loads() (that "converts" json to python dictionary), you can merge them using a similar function :

def dict_merge(dict1, dict2): 
    return(dict2.update(dict1)) 

and then use json.dumps() to serialize the resulting dictionary to json.

Other solution :

you can also use json-merger (installation via pip install json-merger)

pymym213
  • 321
  • 3
  • 10