将有效 JSON 字符串转储为 JSON 的 Pythonic 方法

问题描述 投票:0回答:1

假设我有一个有效的 JSON 字符串,我想将其作为更大的 JSON 对象的一部分。最直接的解决方案是将字符串解析为 dict,然后再次将其转储为 JSON:

import json

json_str = '{"name": "Alice", "age": 30}'

# Write the JSON-encoded string to a string
new_json_str = json.dumps({"foo": "bar", "user": json.loads(json_str)})

解析-转储往返是否可以避免?

我试图避免 如何将有效 json 中的字符串 json 转换为有效 json python

python json
1个回答
0
投票

您可以插入占位符,然后进行简单的字符串替换。

为了避免占位符与真实数据发生冲突,我附加了一个 UUID。

from uuid import uuid4

placeholder = f'PLACEHOLDER_{uuid4()}'
json_with_placeholder = json.dumps({"foo": "bar", "user": placeholder})
new_json_str = json_with_placeholder.replace(json.dumps(placeholder), json_str)

结果:

'{"foo": "bar", "user": {"name": "Alice", "age": 30}}'

我想不出对此有任何警告。鉴于

json_str
是有效的 JSON,我认为不可能输出格式错误的 JSON。

我只能想到优点,比如

json_str
即使不遵循Python对象语义(例如重复名称或浮点精度)也会被保留

json_str = '{"name": "Alice", "age": 30, "age": 30.00000000000000000001}'
© www.soinside.com 2019 - 2024. All rights reserved.