Home > Mobile >  Open a JSON files and edit structure
Open a JSON files and edit structure

Time:11-23

I have produced a couple of json files after scraping a few elements. The structure for each file is as follows:

us.json

{'Pres': 'Biden', 'Vice': 'Harris', 'Secretary': 'Blinken'}

uk.json

{'1st Min': 'Johnson', 'Queen':'Elizabeth', 'Prince': 'Charles'}

I'd like to know how I could edit the structure of each dictionary inside the json file to get an output as it follows:

[
    {"title": "Pres",
    "name": "Biden"}
    ,

    {"title": "Vice",
    "name": "Harris"}
    ,
     {"title": "Secretary",
    "name": "Blinken"}
]

As far as I am able to think how to do it (I'm a beginner, studying only since a few weeks) I need first to run a loop to open each file, then I should generate a list of dictionaries and finally modify the dictionary to change the structure. This is what I got NOT WORKING as it overrides always with the same keys.

import os
import json

list_of_dicts = []
for filename in os.listdir("DOCS/Countries Data"):
    with open(os.path.join("DOCS/Countries Data", filename), 'r', encoding='utf-8') as f:
        text = f.read()
        country_json = json.loads(text)
        list_of_dicts.append(country_json)
        for country in list_of_dicts:
            newdict = country
            lastdict = {}
        for key in newdict:
            lastdict = {'Title': key}
        for value in newdict.values():
            lastdict['Name'] = value
            print(lastdict)

Extra bonus if you could also show me how to generate an ID mumber for each entry. Thank you very much

CodePudding user response:

This look like task for list comprehension, I would do it following way

import json
us = '{"Pres": "Biden", "Vice": "Harris", "Secretary": "Blinken"}'
data = json.loads(us)
us2 = [{"title":k,"name":v} for k,v in data.items()]
us2json = json.dumps(us2)
print(us2json)

output

[{"title": "Pres", "name": "Biden"}, {"title": "Vice", "name": "Harris"}, {"title": "Secretary", "name": "Blinken"}]

data is dict, .items() provide key-value pairs, which I unpack into k and v (see tuple unpacking).

CodePudding user response:

You can do this easily by writing a simple function like below

import uuid
def format_dict(data: dict):
    return [dict(title=title, name=name, id=str(uuid.uuid4())) for title, name in data.items()]

where you can split the items as different objects and add a identifier for each using uuid.

Full code can be modified like this

import uuid
import os
import json

def format_dict(data: dict):
    return [dict(title=title, name=name, id=str(uuid.uuid4())) for title, name in data.items()]

list_of_dicts = []
for filename in os.listdir("DOCS/Countries Data"):
    with open(os.path.join("DOCS/Countries Data", filename), 'r', encoding='utf-8') as f:
        country_json = json.load(f)
        list_of_dicts.append(format_dict(country_json))

# list_of_dicts contains all file contents
  • Related