Home > Software engineering >  complex update of json in python
complex update of json in python

Time:08-29

I have this sample json :

{ "context": "syllabus",
   "subjects":{
     "english":[
      {"english_chapter1.txt":{ "lines":100,
        "complexity":"hard"}
      },
      {"english_chapter2.txt":{ "lines":50,
        "complexity":"easy"}
      }
      ],
    
   "science":[
      {"science_chapter1.txt":{ "lines":90,
        "complexity":"medium"}
      }
      ]
    }
}

This has to updated to the following json structure in python:

{ "context": "syllabus",
   "subjects":{
     "english":["english_chapter1.txt","english_chapter2.txt"],
     "science":["science_chapter1.txt"]
    }
}

any help would be greatly appreciated

CodePudding user response:

You can utilize dictionary and list comprehension in that case.

Which might look like...

# say your original json object to be `original_obj`

# 1. copy original json object
copied_obj = original_obj.copy()


# 2. change structure via for loop
for k, v in original_obj["subjects"].items(): # you can iterate with key and value
    copied_obj["subjects"][k] = [list(ele.keys())[0] for ele in original_obj["subjects"][k]]

CodePudding user response:

You can try something like this:

import json
d=json.loads(j)
for subject in d['subjects']:
    d['subjects'][subject]=[next(iter(i)) for i in d['subjects'][subject]]  #next(iter(i)) would be faster than list(i.keys())[0] to fetch the only key
print(d)

Output:

{'context': 'syllabus', 'subjects': {'english': ['english_chapter1.txt', 'english_chapter2.txt'], 'science': ['science_chapter1.txt']}}
  • Related