【发布时间】:2013-01-29 21:29:37
【问题描述】:
我有一个 JSON 序列化值的 python 字典。
我想添加到这些序列化字符串中,而不先执行loads(...),然后再执行dumps(...) - 所以我“摆弄”了序列化值:
目前我有:
for key, value in my_dict.items():
# creating JSON of additional data I want in the JSON string
extra = dumps({ 'key1': 3, 'key2': 1 }, default=str)
# cutting the last '}' from the end off 'value', the '{' and '}' from the
# start and end of 'extra', and then concatting them together.
my_dict[key] = '%s,%s' % (value[:-1], extra[1:])
我这样做是因为我认为dumps 和loads 是一种浪费,但我目前的方法不是很pythonic。
有没有更好的方法?
注意:“额外”值与初始 JSON 值的来源不同,不能插入到原始数据序列化的位置。
使用约 20 个 JSON blob 的字典时的时间差异:
- 摆弄:0.0005 秒
- json>py>json: 0.0025 秒
快 5 倍
还有 20,000 的乐趣:
- 摆弄':0.333
- json>py>json: 0.813
快 60% 以上
200,000:
- 摆弄':4.5
- json>py>json: 10.25
快 60% 以上
【问题讨论】:
-
查看我的答案更新。使用 C 库来反序列化 JSON 比摆弄字符串要快得多。
标签: python json serialization