首页 > 解决方案 > Python缩进字符串到JSON

问题描述

Python我有一个格式为:

header:
    hello: world
    world: hello
    this:
        is: difficult
    this: 2

我想转换成JSON

{ header: { hello: world, world: hello, this: { is: difficult} }}

这可能以一种有效的方式吗?

我试过了,yaml.load(str)但不能处理。

更新

我已经用空格替换了制表符,这yaml不会失败。

我的最后一个问题是,在我的原始字符串/对象中,我可以有重复的键。不知道如何处理这个问题yaml,但它的顺序是随机的,所以我想保留所有键,或者将包含对象的键作为值优先于包含简单整数的键。有道理,有什么办法处理吗?

标签: pythonjsonpython-3.xstringyaml

解决方案


YAML 对我来说很好用......

test="""header:
    hello: world
    world: hello
    this:
        is: difficult"""

print(test)

'标题:\n你好:世界\n世界:你好\n这个:\n是:困难'

import yaml
yaml.load(test)

{'header': {'hello': 'world', 'world': 'hello', 'this': {'is': '困难'}}}


推荐阅读