简体   繁体   中英

Converting JSON to nested dictionary(python)

I have a json object like this:

{

parser_config:

[{"element_name": "jobs","type": "class", "attributes": ["title is-5", "company", "location"]},

{"element_name": "page-details","type":"class","attributes":["subtitle is-3", "title is-1"]}]

}

I want to create a nested dictionary out of the attributes like this:

{"jobs": {"class": "title is-5", "class_2": "location", "class_3": "company"},

 "page-details": {"class": "subtitle is-3", "class_2": "title is-1"}}

I have created a function like this:

def AttributeConstructor(json_data: dict, attribute_type: str) -> dict:
specific_attributes = []
config_data = json_data['parser_config']
for i in range(len(config_data)):
    for target in config_data[i]['attributes']:
        target_type = config_data[i]['type']
        if target_type == attribute_type:
            element_name = config_data[i]['element_name']
            specific_attributes.append(
                {element_name: {target_type: target}})
return specific_attributes

I am not sure how to get the desired output of keeping 1 element name for all {target_type: target}. I am setting attribute_type to "class".

The goal is to convert the JSON into a nested dictionary using a function, I cannot seem to get my function to output everything so I am left with:

{"jobs": {"class": "company"},

 "page-details": {"class": "title is-1"}}

instead of the whole nested dictionary. I also would like this to work on much larger JSON objects.

You only add singelton dictionaries {element_name: {target_type: target}} to the list.

You could try

def attribute_constructor(json_data, attribute_type):
    return [
        {rec["element_name"]: {
            rec["type"] if i == 1 else f'{rec["type"]}_{i}': attr
            for i, attr in enumerate(rec["attributes"], start=1)}}
        for rec in json_data['parser_config'] if rec["type"] == attribute_type
    ]

or more closer to your attempt

def attribute_constructor(json_data, attribute_type):
    specific_attributes = []
    for rec in json_data['parser_config']:
        target_type = rec["type"]
        if target_type != attribute_type:
            continue
        specific_attributes.append(
            {rec["element_name"]: {
                target_type if i == 1 else f'{target_type}_{i}': attr
                for i, attr in enumerate(rec["attributes"], start=1)}}                
        )
    return specific_attributes

instead.

Result for

json_data = {
    "parser_config": [
        {"element_name": "jobs", "type": "class", "attributes": ["title is-5", "company", "location"]},
        {"element_name": "page-details", "type": "class","attributes": ["subtitle is-3", "title is-1"]}
    ]
}
print(attribute_constructor(json_data, "class"))

is

[{'jobs': {'class': 'title is-5', 'class_2': 'company', 'class_3': 'location'}},
 {'page-details': {'class': 'subtitle is-3', 'class_2': 'title is-1'}}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM