如何将JSON值放入Python列表中

时间:2017-07-18 18:37:36

标签: python

我有一个如下所示的json列表:

{
    "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"
        }
    ]
}

我的实际数据在列表中有很多json对象,我想知道如何将数字放在" date"之间。和"区"在json中的单独列表中。 json对象之间的数字不同,但它们总是在" date"之间。和"区"值。

我该怎么做才能把它变成这个:

{
    "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"
        }
    ]
}

2 个答案:

答案 0 :(得分:2)

您可以通过设置成员资格对它们进行排序(如PM 2Ring所述,设置成员资格更快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

结果(注意没有订购词典):

>>> 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'}

答案 1 :(得分:1)

使用内置int()函数检查整数键:

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)

现在,使用new_list等内容打印json.dumps()会产生类似的结果:

[
    {
        "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"
    }
]