Jose Ramon
Jose Ramon

Reputation: 5386

Nested json in python

I've a face detection code. What I want is to store metadata in json files in specific order. Basically I want to write how many faces exists in an image and the location of images. My code is the following:

data =[] 
data.append({'number_of_faces':len(faces)}) 
nested_data = []
for (x,y,w,h) in faces:
    nested_data.append({'face_x': x, 'face_y': y, 'face_h': h, 'face_w': w})
data.append(nested_data)
with open(json_path+folder+'/'+file_name, "w") as outfile:
        json.dump(data, outfile)    

The output is, for example:

[
    {
        "number_of_faces": 1
    },
    [
        {
            "face_h": 38,
            "face_w": 38,
            "face_x": 74,
            "face_y": 45
        }
    ]
]

However I want to create a nested json. Thus I want after number_of_faces object to have nested all face_location inside number_of_faces {}. How is it possible to do so?

Upvotes: 0

Views: 190

Answers (2)

Vincent Beltman
Vincent Beltman

Reputation: 2114

data = {}
data['number_of_faces'] = len(faces)
data['faces'] = []
for (x,y,w,h) in faces:
    data['faces'].append({'face_x': x, 'face_y': y, 'face_h': h, 'face_w': w})
with open(json_path+folder+'/'+file_name, "w") as outfile:
    json.dump(data, outfile)  

This will have the output:

{
    'number_of_faces': 4
    'faces':[{
        'face_x': 'x',
        'face_y': 'y',
        'face_h': 'h',
        'face_z': 'z'
    }]
}

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599956

First of all, as I said in the comment, let's ignore the JSON part. This is a question about lists and dicts only. So, we just need to build up the data in the way you want.

To start with, rather than just appending to a list, we should start with a dict for each shape. Then, we can add the face data for each shape inside that dict.

data = []
for shape in shapes:
    shape = {'number_of_faces':len(faces)}
    nested_data = []
    for (x,y,w,h) in faces:
        nested_data.append({'face_x': x, 'face_y': y, 'face_h': h, 'face_w': w})
    shape['face_location'] = nested_data
    data.append(shape)

Upvotes: 1

Related Questions