YAML 结构 key/value 格式为 JSON

YAML structured on key/value format to JSON

我在下面有这个 yaml 文件。我需要保留 yaml 文件的这种结构。 在文件中有一些嵌套的 key/values(如 personalinfo and more)和一些没有值的嵌套键(如 extra)的特殊性。
key/value 的数量是任意的,因为 parents 的数量也是任意的(在本例中 parents 是 personalInfo, more, extra)。

name: person1
personalInfo:
  - key: address
    value: street 1
  - key: age
    value: 10
  - key: school
    value: XYZ
more:
  - key: mother
    value: Samantha
extra:
 - key: a
 - key: b

我想从这个 yaml 生成一个 Json 格式如下,但我不知道如何实现。

'{"personalInfo" : {"address": "street 1", "age": "10", "school": "XYZ"}, "more":{"mother": "Samantha"}, "extra": ["a", "b"]}' "localhost:8080/person1"

最简单纯粹的方法是PyYaml,可以通过pip install pyyaml安装。存在一个普通的 yaml.load() 函数,但 yaml.safe_load() 应该始终是首选,除非您明确需要提供的任意对象 serialization/deserialization 以避免引入任意代码执行的可能性。

import yaml
with open("test.yml", 'r') as stream:
    try:
        data = yaml.safe_load(stream)
    except yaml.YAMLError as exc:
        print(exc)

这个returns:

{'name': 'person1',
 'personalInfo': [{'key': 'address', 'value': 'street 1'},
  {'key': 'age', 'value': 10},
  {'key': 'school', 'value': 'XYZ'}],
 'more': [{'key': 'mother', 'value': 'Samantha'}],
 'extra': [{'key': 'a'}, {'key': 'b'}]}

您可以试试这个以获得您想要的结果:

import json

new_data = {}

for i in data:
    if i!='name':    
        temp = {}
        val = []
        for k in data[i]:
            if 'key' in k:
                try:
                    temp[k['key']] = k['value']
                except:
                    val.append(k['key'])
        if val:
            new_data[i] = val
        elif temp:
            new_data[i] = temp
        else:
            new_data[i] = data[i]

str1 = json.dumps(new_data)
str2 = "localhost:8080/"+data['name']

with open("sample.json", "w") as outfile:
    json.dump(str1.replace('"', "'"), outfile)
    json.dump(str2.replace('"', "'"), outfile)

结果 sample.json

"{'personalInfo': {'address': 'street 1', 'age': 10, 'school': 'XYZ'}, 'more': {'mother': 'Samantha'}, 'extra': ['a', 'b']}""localhost:8080/person1"