0

Is there a way to convert a json that looks like this:

{
    "id": "1",
    "object": [{
        "object_1": "hi",
        "object_2": "hello"
    },
    {
        "object_1": "hello",
        "object_2": "hi"
    }]
}

Into something where I can store within each dictionary the parent id without having to change the names like this?

{
"id": "1",
"object_1": "hi",
"object_2": "hello"
},
{"id": "1",
"object_1": "hi",
"object_2": "hello"
}
martineau
  • 119,623
  • 25
  • 170
  • 301
user7298979
  • 499
  • 4
  • 21

1 Answers1

1

There are many ways how you can convert the dictionary. For example, use generator:

d = {
    "id": "1",
    "object": [{
        "object_1": "hi",
        "object_2": "hello"
    },
    {
        "object_1": "hello",
        "object_2": "hi"
    }]
}
    
def flatten_dict(d):
    for o in d['object']:
        yield {
            'id': d['id'],
            **o
        }

print(list(flatten_dict(d)))

Prints:

[{'id': '1', 'object_1': 'hi', 'object_2': 'hello'}, {'id': '1', 'object_1': 'hello', 'object_2': 'hi'}]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Exactly what I was looking for, thanks a lot @andrejKesely, this is a duplicate question since it was covered previously but you kept the object names the same which is exactly what I needed – user7298979 Oct 12 '20 at 20:29