2

我正在以给定格式从服务器中提取一些 JSON:

{"images": [{"rating": 5.0, "thumburl": "http://something.jpg", "description": "dfgd", "submitdate": "2011-01-29T07:54:02", "submituser": "J", "imagekey": "a"}, ...]}

我必须使用“imagekey”为每个元素添加一个新元素“viewurl”。例如,结果将是

{"images": [{"rating": 5.0, "thumburl": "http://something.jpg", "description": "dfgd", "submitdate": "2011-01-29T07:54:02", "submituser": "J", "imagekey": "a", "viewurl": "/view?imagekey=a"}, ...]}

可能有一种简单的方法可以做到这一点,但是除了转储和加载之外,我在 simplejson 上找不到很多东西。

4

4 回答 4

4

这是你想要做的吗?

data = simplejson.loads(yourString)
for image in data['images']:
    image['viewurl'] = '/view?imagekey=%s' %(image['imagekey'])

您也可以使用object_hook。这适用于您的示例,但您可能需要根据实际数据对其进行一些调整:

>>> def addImageKey(dataPart):
...     if dataPart.has_key('imagekey'):
...         dataPart['viewurl'] = '/view?imagekey=%s' %dataPart['imagekey']
...     return dataPart
... 
>>> decoded_with_viewurl = json.loads(myString, object_hook = addImageKey)

我提到可能需要调整它的原因是因为在它的当前形式中,addImageKeyobject_hook 会将 viewurl 键/值添加到 JSON 结构中imagekey已经包含键的任何对象。因此,如果需要,您可能必须使用更具体的项目images

哦,如果你想将它编码回 JSON 字符串,你可以将最后一行更改为

>>> reencoded_with_viewurl = json.dumps(json.loads(myString, object_hook = addImageKey))

根据您正在解码/编码的数据量,我建议使用 cjson 重新编码数据的可能性。与 simplejson/json 相比,它快如闪电。不幸的是,它不支持 object_hook 之类的东西。

于 2011-02-01T05:05:14.217 回答
2

我想最简单的方法是将它放入 python,对其进行操作,然后将其转储回 JSON:

>>> import simplejson
>>> data = simplejson.loads('''{"images": [{"rating": 5.0, "thumburl": "http://something.jpg", "description": "dfgd", "submitdate": "2011-01-29T07:54:02", "submituser": "J", "imagekey": "a"}]}''')
>>> for image in data['images']:
    key = image['imagekey']
    image["viewurl"] = "/view?imagekey=%s" % key


>>> outdata = simplejson.dumps(data)
于 2011-02-01T05:05:31.810 回答
1

我能想到的最简单的方法就是使用simplejson反序列化为原生python,修改原生python,再序列化回json。

于 2011-02-01T05:04:57.243 回答
0

好吧,你有两个选择。在字符串上使用正则表达式或将 JSON 解析为 Python 对象,然后使用该imageurl值创建一个新属性,然后生成另一个 JSON 字符串。

于 2011-02-01T05:04:19.873 回答