如何在python中将yaml键值链接到json键值

2024-05-01 22:08:30 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我想在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"
}

Tags: 文件namejsonyamlpackagefooaddressbirthdate
1条回答
网友
1楼 · 发布于 2024-05-01 22:08:30

为了安全起见,首先加载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.loadjson.dump来读/写文件,而不是字符串。请注意,加载和写入JSON数据可能会更改对象中项目的顺序(无论如何,您都不应该依赖于此)。你知道吗

相关问题 更多 >