j doe
j doe

Reputation: 233

How to put JSON values into a list Python

I have a json list that looks like this:

{
    "callback": [{
            "id": "R_puFk4fZ8m1lE4bD",
            "set": "Default Response Set",
            "ace": "asdf",
            "date": "asdfdsa",
            "1": "asdf",
            "2": "s",
            "3": "3",
            "4": "1",
            "zone": "0",
            "long": "33.564498901367",
            "lat": "-112.00869750977"
        }
    ]
}

My actual data has a lot of json objects within the list and I am wondering how I would put the numbers between "date" and "zone" in a separate list within the json. The numbers vary between the json objects, but they are always in between the "date" and "zone" values.

What would I do to transform it into this:

{
    "callback": [{
            "id": "R_puFk4fZ8m1lE4bD",
            "set": "Default Response Set",
            "ace": "asdf",
            "date": "asdfdsa",
            "Q": [
                "1": "asdf",
                "2": "s",
                "3": "3",
                "4": "1"
            ],
            "zone": "0",
            "long": "33.564498901367",
            "lat": "-112.00869750977"
        }
    ]
}

Upvotes: 2

Views: 845

Answers (2)

TemporalWolf
TemporalWolf

Reputation: 7952

You can sort them out via set membership (as PM 2Ring mentioned, set membership is faster O(1)):

def group_questions(source_dct):
    meta_tags = {"id", "set", "ace", "date", "zone", "long", "lat"}

    result_dct = {"Q": {}}
    for key in source_dct:
        if key not in meta_tags:
            result_dct["Q"][key] = source_dct[key]
        else:
            result_dct[key] = source_dct[key]
    return result_dct

Result (note dictionaries are not ordered):

>>> print group_questions(dct)
{'set': 'Default Response Set', 
 'ace': 'asdf', 
 'zone': '0', 
 'long': '33.564498901367', 
 'Q': {'1': 'asdf', 
       '3': '3', 
       '2': 's', 
       '4': '1'}, 
 'lat': '-112.00869750977', 
 'date': 'asdfdsa', 
 'id': 'R_puFk4fZ8m1lE4bD'}

Upvotes: 2

Sam Chats
Sam Chats

Reputation: 2321

Use the built-in int() function to check for integer keys:

new_list = []
for old_data in old_list: #old_list is the value of 'callback' key
    data = {'Q': {}}
    for key in old_data.keys():
        try:
            num = int(key)
            data['Q'][key] = old_data[key]
        except ValueError: # stringy keys
            data[key] = old_data[key]
    new_list.append(data)

Now, printing new_list using something like json.dumps() will give something like:

[
    {
        "Q": {
            "1": "asdf",
            "2": "s",
            "3": "3",
            "4": "1"
        },
        "id": "R_puFk4fZ8m1lE4bD",
        "set": "Default Response Set",
        "ace": "asdf",
        "date": "asdfdsa",
        "zone": "0",
        "long": "33.564498901367",
        "lat": "-112.00869750977"
    }
]

Upvotes: 1

Related Questions