MNav
MNav

Reputation: 23

Parsing multi-level json file into Python dict

I'm trying to parse a json file into a python dict (to make it copy-ready for Redshift).

My intended output format is:

{col1:val1, col2:val2,..}
{col1:val1, col2:val2,..}

The current format of the file is:

{"val0": {"col1":"val1", "col2":"val2",..},
 "val0": {"col1":"val1", "col2":"val2",..},..}

Where "val0" is a date field (only value, no column name) that I don't need in my output.

How do I convert the latter format to the former? I've tried going through documentation for the json module (as well as a few other StackOverflow answers), but nothing seems to click. Any help is appreciated. Thanks!

Upvotes: 1

Views: 1627

Answers (1)

brennan
brennan

Reputation: 3493

It sounds like you need a json array.

import json


with open('example.json', 'r') as f:
    data = json.load(f)

array_data = list(data.values())

print(array_data)  # [{'col1': 'val1', 'col2': 'val2'},
                   #  {'col1': 'val1', 'col2': 'val2'}]

with open('array_result.json', 'w') as f:
    json.dump(array_data, f)

Upvotes: 1

Related Questions