Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add parent object in JSON with python

I have this json which has 3 parents and several child elements under each parent. I want to add one more common parent for all 3 current parents.

Currently I have:

 {
  "Parent1": {
    "Key1": "Value",
    "Key2": "Value",
    "Key3": "Value"
},
  "Parent2": {
    "Key1": "Value",
    "Key2": "Value",
    "Key3": "Value"
  },
  "Parent3": {
    "Key1": "Value",
    "Key2": "Value",
    "Key3": "Value"
  }
}

What I want to have:

{
  "Main parent": {
    "Parent1": {
      "Key1": "Value",
      "Key2": "Value",
      "Key3": "Value"
    },
    "Parent2": {
      "Key1": "Value",
      "Key2": "Value",
      "Key3": "Value"
    },
    "Parent3": {
      "Key1": "Value",
      "Key2": "Value",
      "Key3": "Value"
    }
  }
}

Below python3 code doesn't do the job:

with open ("myfile.json", 'r') as f:
    myjson = json.load(f)

myjson["Main Parent"] = myjson

I would appreciate if you spread some light on this situation.

like image 989
Mher Harutyunyan Avatar asked Dec 18 '22 23:12

Mher Harutyunyan


2 Answers

with open ("myfile.json", 'r') as f:
    myjson = json.load(f)

myjson = {'Main Parent': myjson}
like image 68
Marco Pantaleoni Avatar answered Jan 04 '23 23:01

Marco Pantaleoni


You could just create a new dict and map Main Parent to your child JSON:

new_json = dict()
new_json["Main Parent"] = myjson
like image 37
TayTay Avatar answered Jan 04 '23 23:01

TayTay