如何在Python循环中保存和追加响应JSON作为单个对象?

时间:2015-07-05 18:02:15

标签: python json

我有一个调用JSON Web服务的脚本。我每次调用只能收到100条记录,但是,我需要在我的脚本中稍后将每个响应写入NumPy数组,如何成功地将多个JSON响应作为单个JSON的结构附加来处理此任务?

现在,下面的脚本将每个响应返回为decoded2。所以第一个响应是decoded2,第二个响应也会decoded2覆盖第一个响应。

如何处理这两个响应并生成一个巨大的JSON对象?下面的示例JSON显示了decoded2的上层打印的内容。所以我想将每个输出中的所有LISTS OF DICTIONARIES附加为decoded2

现在唯一写为decoded2的数据是lastpage参数为'true'的最后一个字典。

while lastpage == 'false':
    r2 = requests.post(url2, data=data2, headers=headers2)
    print r2.text
    decoded2 = r2.json()
    f2 =open('C:\Users\GeoffreyWest\Desktop\Request.json')
    data2 = jsonpickle.decode((f2.read()))
    if decoded2['Response']['LastPage'] == 'false':
        data2['QueryRequest']['PageSize'] = pagesize
        startrow = startrow + data2['QueryRequest']['PageSize']
        data2['QueryRequest']['StartRowNum'] = startrow
        data2['QueryRequest']['NewQuery'] = 'false'
        data2 = jsonpickle.encode(data2)
        print startrow
    else:
        lastpage = 'true'

输出示例:

    {
        "status": {
            "code": 311,
            "message": "Service Request Successfully Queried.",
            "cause": ""
        },
        "Response": {
            "LastPage": "false",
            "NumOutputObjects": "100"
        }
    }
    #multiple json dicts within lists 


    {
        "status": {
            "code": 311,
            "message": "Service Request Successfully Queried.",
            "cause": ""
        },
        "Response": {
            "LastPage": "false",
            "NumOutputObjects": "100"
        }
    }
    #multiple json dicts within lists 




Desired Output:

{
    "status": {
        "code": 311,
        "message": "Service Request Successfully Queried.",
        "cause": ""
    },
    "Response": {
        "LastPage": "true",
        "NumOutputObjects": "76"
    }
}
#multiple json dicts within lists from JSON # 1
#multiple json dicts within lists from JSON # 2
#multiple json dicts within lists from JSON # 3

0 个答案:

没有答案