skip to Main Content

I am trying to insert parent object in the json but it inserts it on the top but I want to insert after particular key present in the json. I tried adding below code but it insert parent at the top (I understand since it is parent it will be inserted on the top but i want to insert before particular key in this case key is "pattern" :

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

myjson = {'Main Parent': myjson}

Basically I want to insert "versions": before "pattern"

"versions":{
           "pattern": {
             "provider": "abc",
             "schema": "xyz" 
           },
           "baseline":{
              "version" : "dev"
           }
       }   

Input json file

    {
          "target": {
             "Name": "abc",
             "Occupation": "xyz" 
           },
           "properties":{
              "env" : "dev"
           },
           "use_it": "xyz",
           "pattern": {
             "provider": "abc",
             "schema": "xyz" 
           },
           "baseline":{
              "version" : "dev"
           }   
    }

Expected output json file

Input json file

    {
          "target": {
             "Name": "abc",
             "Occupation": "xyz" 
           },
           "properties":{
              "env" : "dev"
           },
           "use_it": "xyz",
        "versions":{
           "pattern": {
             "provider": "abc",
             "schema": "xyz" 
           },
           "baseline":{
              "version" : "dev"
           }
       }   
    }

2

Answers


  1. Would something like this work for you?

    import json
    
    with open ("myfile.json", 'r') as f:
        myjson = json.load(f)
    
    # Add any top level keys you want to move into the `versions` key
    versions_keys = [
        "pattern", "baseline"
    ]
    
    myjson["versions"] = {}
    
    for version_key in versions_keys:
        key = myjson.pop(version_key)
        myjson["versions"][version_key] = key
    
    myjson = {'Main Parent': myjson}
    
    print(json.dumps(myjson, indent=4))
    

    The pop method deletes a key from a dict and returns its value.
    We store that value and place it back under the new "versions" key.

    Output:

    {
        "Main Parent": {
            "target": {
                "Name": "abc",
                "Occupation": "xyz"
            },
            "properties": {
                "env": "dev"
            },
            "use_it": "xyz",
            "versions": {
                "pattern": {
                    "provider": "abc",
                    "schema": "xyz"
                },
                "baseline": {
                    "version": "dev"
                }
            }
        }
    }
    
    Login or Signup to reply.
  2. yes,you can dynamically get the keys from the versions dictionary and insert them before the "pattern" key in your JSON!

    check this out too:

    import json
    
    with open("myfile.json", "r") as f:
        myjson = json.load(f)
    
    versions = {
        "pattern": {
            "provider": "abc",
            "schema": "xyz"
        },
        "baseline": {
            "version": "dev"
        }
    }
    
    index = list(myjson).index("pattern")
    
    updated_json = {}
    
    for i, (key, value) in enumerate(myjson.items()):
        if key == "pattern":
            updated_json["versions"] = versions
        updated_json[key] = value
    
    with open("myfile.json", "w") as f:
        json.dump(updated_json, f, indent=4)
    

    as you see,the versions dictionary is defined with the desired key-value pairs,and during the iteration through the original JSON, when the pattern key is encountered, the versions dictionary is inserted before it!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search