5

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.

0

2 Answers 2

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

myjson = {'Main Parent': myjson}
Sign up to request clarification or add additional context in comments.

2 Comments

@panta, Thanks for the answer, I am getting the backslash \ in the JSON file when I try above solution. could you please let me know how can fix this?
@SaurabhBade maybe you have some characters that need quoting inside you json? (Other quotes, ...)
5

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

new_json = dict()
new_json["Main Parent"] = myjson

3 Comments

Thank you very much. this does the job but below answer does it with one less row
@Tgsmith61591, Thanks for the answer, I am getting the backslash \ in the JSON file when I try above solution. could you please let me know how can fix this?
Traceback (most recent call last): File "<string>", line 24, in <module> ValueError: Couldn't fix JSON [Program finished]if we don't add [] at the start/end of data and try to parse it, also if we validate we get {'Parent1': {'Key1': 'Value', 'Key2': 'Value', 'Key3': 'Value'}, 'Parent2': {'Key1': 'Value', 'Key2': 'Value', 'Key3': 'Value'}, 'Parent3': {'Key1': 'Value', 'Key2': 'Value', 'Key3': 'Value'}} [Program finished] meaning the example you posted looks good. Maybe some issues with the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.