您好我想在json中使用yaml数据 例如。
json文件:
{
"Name": "foo",
"Birthdate": "1/1/1991",
"Address": "FOO_ADDRESS",
"Note": "Please deliver package to foo at FOO_ADDRESS using COURIER service"
}
yaml文件:
--- FOO_ADDRESS: "foo lane, foo state" COURIER: "foodex"
有人可以指导我最有效的方法吗?在这个特定的例子中,我真的不需要使用单独的yaml文件(我理解)。但在我的具体情况下,我可能不得不这样做。
编辑:抱歉,我没有粘贴所需的输出文件
应该是这样的:
{
"Name": "foo",
"Birthdate": "1/1/1991",
"Address": "foo lane, foo state",
"Note": "Please deliver package to foo at foo lane, foo state using foodex service"
}
答案 0 :(得分:0)
为安全起见,首先加载JSON,然后在加载的字符串中进行替换。如果在JSON源中执行替换,则最终可能会出现无效的JSON输出(当替换字符串包含"
或其他必须在JSON中转义的字符时。)
import yaml, json
def doReplacements(jsonValue, replacements):
if isinstance(jsonValue, dict):
processed = {doReplacements(key, replacements): \
doReplacements(value, replacements) for key, value in \
jsonValue.iteritems()}
# Python 3: use jsonValue.items() instead
elif isinstance(jsonValue, list):
processed = [doReplacements(item, replacements) for item in jsonValue]
elif isinstance(jsonValue, basestring):
# Python 3: use isinstance(jsonValue, str) instead
processed = jsonValue
for key, value in replacements.iteritems():
# Python 3: use replacements.items() instead
processed = processed.replace(key, value)
else:
# nothing to replace for Boolean, None or numbers
processed = jsonValue
return processed
input = json.loads("""{
"Name": "foo",
"Birthdate": "1/1/1991",
"Address": "FOO_ADDRESS",
"Note": "Please deliver package to foo at FOO_ADDRESS using COURIER service"
}
""")
replacements = yaml.safe_load("""---
FOO_ADDRESS: "foo lane, foo state"
COURIER: "foodex"
""")
print json.dumps(doReplacements(input, replacements), indent=2)
# Python 3: `(...)` around print argument
使用json.load
和json.dump
来读取/写入文件而不是字符串。请注意,加载和写入JSON数据可能会更改对象中项目的顺序(您不应该依赖它)。