使用Python将JSONObject转换为JSONArray

时间:2014-12-05 23:33:41

标签: java python json

我已经完成了各种各样的线程,但是在python中找不到特定的答案。 我有一个json文件

{
    "StoreID" : "123",
    "Status" : 3,
    "data" : {
            "Response" : {
                    "section" : "25",
                    "elapsed" : 277.141,
                    "products" : {
                            "prd_1": {
                                    "price" : 11.99,
                                    "qty" : 10,
                                    "upc" : "0787493"
                            },
                            "prd_2": {
                                    "price" : 9.99,
                                    "qty" : 2,
                                    "upc" : "0763776"
                            },
                            "prd_3": {
                                    "price" : 29.99,
                                    "qty" : 8,
                                    "upc" : "9948755"
                            }
                    },
                    "type" : "Tagged"
            }
    }
}

我需要通过更改json对象'产品来将此json文件转换为下面的格式。成阵列形式。

{
    "StoreID" : "123",
    "Status" : 3,
    "data" : {
            "Response" : {
                    "section" : "25",
                    "elapsed" : 277.141,
                    "products" : [
                            {
                                    "price" : 11.99,
                                    "qty" : 10,
                                    "upc" : "0787493"
                            },
                            {
                                    "price" : 9.99,
                                    "qty" : 2,
                                    "upc" : "0763776"
                            },
                            {
                                    "price" : 29.99,
                                    "qty" : 8,
                                    "upc" : "9948755"
                            }
                    ],
                    "type" : "Tagged"
            }
    }
}

有没有什么好方法在python中做到这一点。大多数情况下,我看到人们正在使用java,但不是在python中。你能告诉我一个在python中做到这一点的方法。

2 个答案:

答案 0 :(得分:1)

只需获取产品字典的值(),即可获得一系列值。假设你的json在file1.txt中,下面的代码可以解释我的注意事项

import json
with open('file1.txt') as jdata:
    data = json.load(jdata)
    d = data
d["data"]["Response"]["products"] = d["data"]["Response"]["products"].values()
print(json.dumps(d))

<强>输出:

{"Status": 3, "StoreID": "123", "data": {"type": "Tagged", "Response": {"section": "25", "products": [{"price": 9.99, "upc": "0763776", "qty": 2}, {"price": 29.99, "upc": "9948755", "qty": 8}, {"price": 11.99, "upc": "0787493", "qty": 10}], "elapsed": "277.141"}}}

答案 1 :(得分:0)

这样的事情对你有用吗?

import json
import copy

a = json.load(open("your_data.json", "r"))

b = copy.deepcopy(a)

t =  a.get('data').get('Response').get('products')
b['data']['Response']['products'] = t.values()    # Originally was: [t[i] for i in t]

您可以使用json.dumps(b)

返回JSON