提问人:John 提问时间:11/15/2023 更新时间:11/15/2023 访问量:24
Jinja - 将 JSON 转换为 YAML
Jinja - Converting JSON to YAML
问:
我正在尝试将我的 JSON 输入转换为 YAML 格式。我只需要 json 中几个字段的键值对,但我没有看到我需要的输出。在我的 YAML 中,我需要作为键值的字段是作为键的字段和作为值的字段。name
value
JSON 输入:
{
"Test":{
"id":223,
"name":"Test",
"value":"None",
"propertyId":223,
"parentId":"None",
"children":[
{
"Test 2":{
"id":260,
"name":"Test 2",
"value":"Connected",
"propertyId":260,
"parentId":223,
"children":[
{
}
]
},
"This is a test":{
"id":1058,
"name":"This is a test",
"value":"",
"propertyId":1058,
"secured":0,
"parentId":223,
"children":[
{
}
]
},
"Info":{
"id":1270,
"name":"Info",
"value":"",
"propertyId":1270,
"secured":0,
"parentId":223,
"children":[
{
"More info":{
"id":1271,
"name":"More info",
"value":"N/A",
"propertyId":1271,
"secured":0,
"parentId":1270,
"children":[
{
}
]
},
"Another info":{
"id":1272,
"name":"Another info",
"value":"",
"propertyId":1272,
"secured":0,
"parentId":1270,
"children":[
{
"We Got more":{
"id":1273,
"name":"We Got more",
"value":"",
"propertyId":1273,
"secured":0,
"parentId":1272,
"children":[
{
}
]
}
}
]
}
}
]
}
}
]
}
}
金贾代码:
{% macro transform(item) %}
{% set result = {} %}
{% for key, value in item.items() %}
{% if value is mapping %}
{% set result = result | combine(transform(value)) %}
{% else %}
{% set result = result | combine({item['name']: item['value']}) %}
{% endif %}
{% endfor %}
{{ result }}
{% endmacro %}
{{ transform(['Test']) | to_yaml(indent=2) | safe }}
Jinja的电流输出:
' {}
'
答: 暂无答案
评论