1

I'm new to Python and haven't been coding for a while. Is there a way to convert a element in a JSON structure to an array?

Example

Given:

{
    "persons": 
        {
            "city": "Seattle", 
            "name": "Brian"
        }
}

Required:

{
    "persons": [
        {
            "city": "Seattle", 
            "name": "Brian"
        }
    ]
}

Background: I want to insert a JSON into a Big Query Table using repeating records. But the fields are not required to be repeating, it just happens in some cases. As soon I have a array everything works fine, if the array is missing, an error is returned. Now I'm looking for some python function where I just can say make my persons element an array with one element.

Best regards

Edit:

to get a bit more concrete: My structure looks like following.

{
"a" : {
    "b" : [
        {
            "c" : {
                "foo" : "bar",
                ...
            },
            "d" : {
                "foo" : "bar",
                ...
            },
            "e" : "bar"
        },
        {
            "c" : [
                {
                    "foo" : "bar",
                    ...
                },
                {
                    "foo" : "bar",
                    ...
                },
                {
                    "foo" : "bar",
                    ...
                },
                {
                    "foo" : "bar",
                    ...
                },
                {
                    "foo" : "bar",
                    ...
                }
            ],
            "d" : {
                "foo" : "bar",
                    ...
            },
            "e" : "bar"
        },
        {
            "c" : {
                "foo" : "bar",
                ...
            },
            "d" : {
                "foo" : "bar",
                ...
            },
            "e" : "bar"
        }
    ]
},
"f" : {
    "foo" : "bar",
    ....
}

}

b and c can be repeated but they don't have to. Anyway I need both of the elements as an array. Best way would be a reusable function with the JSON, b and c as input as we have different JSON files with different structures.

Currently I try to use @ajrwhite approach to achieve my requierements but I'm struggeling a bit.

7
  • 3
    show us what have you done till now. Your piece of code. Commented Mar 19, 2019 at 12:50
  • use json module Commented Mar 19, 2019 at 12:50
  • in your example "persons" is a list with a single item, a dictionary. is this what you want? you can convert the JSON to a python object and mess with it however you want, use the JSON module Commented Mar 19, 2019 at 12:50
  • You can cast the dictionnary into an array such as value = [value] Commented Mar 19, 2019 at 12:51
  • 1
    Are you just after - d['persons'] = [d['persons']] ? Commented Mar 19, 2019 at 12:51

2 Answers 2

2

This is a common issue with working with deeply-nested JSON-style structures in Python (e.g. with MongoDB extracts).

Here is a recursive approach which wraps all dicts contained within one large dict in []:

def listify_dict(var):
    if isinstance(var, dict):
        output_dict = var.copy()
        for k, v in var.items():
            output_dict[k] = listify_dict(v)
        return [output_dict]
    elif isinstance(var, list):
        output_list = var.copy()
        for i, v in enumerate(output_list):
            output_list[i] = listify_dict(v)
        return output_list
    else:
        return var

Example:

test = {
    "persons": 
        {
            "city": "Seattle", 
            "name": "Brian"
        }
}
listify_dict(test)

Output:

[{'persons': [{'city': 'Seattle', 'name': 'Brian'}]}]
Sign up to request clarification or add additional context in comments.

Comments

2

You can change the particular element to list and re-assign:

j_data = {
    "persons":
        {
            "city": "Seattle",
            "name": "Brian"
        }
}

j_data['persons'] = [j_data['persons']]
print(j_data)

OUTPUT:

{'persons': [{'city': 'Seattle', 'name': 'Brian'}]}

Pretty printing with the indent parameter:

j_data = {
    "persons":
        {
            "city": "Seattle",
            "name": "Brian"
        }
}

j_data['persons'] = [j_data['persons']]
import json
print(json.dumps(j_data, indent=4, sort_keys=True))

OUTPUT:

{
    "persons": [
        {
            "city": "Seattle",
            "name": "Brian"
        }
    ]
}

EDIT:

Incase you want to convert all the elements to list, a simple loop would do it:

j_data = {
    "persons":
        {
            "city": "Seattle",
            "name": "Brian"
        },
    "cars":
        {
            "car1": "Tesla",
            "car2": "Toyota"
        }
}

for elem in j_data:
    j_data[elem] = [j_data[elem]]
# print(j_data)
import json
print(json.dumps(j_data, indent=4, sort_keys=True))

OUTPUT:

{      
    "persons": [
        {
            "city": "Seattle",
            "name": "Brian"
        }
    ],
     "cars": [
        {
            "car1": "Tesla",
            "car2": "Toyota"
        }
    ]
}

7 Comments

This is the manual approach, but I think user needs something that can be automated across a larger structure?
@ajrwhite Edited for it :)
Yes this works on the example, but JSON structures are often deeply nested, so a top-level loop over the items won't work. See my answer for a recursive approach stackoverflow.com/a/55241895/5447172
@ajrwhite Indeed, but it looks like the top-level element manipulation from the question. Awaiting OP's response.
sure - not criticising your answer. I may be assuming too much from the question. My experience of JSON is that in practice you are often trying to apply this cleaning at varying levels of depth, and it often makes sense to use recursion.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.