【问题标题】:Python indent string to JSONPython缩进字符串到JSON
【发布时间】:2020-06-25 16:45:42
【问题描述】:

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 处理这个问题,但它的顺序是随机的,所以我想保留所有键,或者将包含对象的键作为值优先于包含简单整数的键。有道理,有什么办法处理吗?

【问题讨论】:

  • 你是如何使用 yaml 的?我已经尝试过了,它完全按照要求加载。
  • 所需的输出不是 JSON,因为它缺少引号。是这个问题吗?你可以json.dumps通过yaml.load加载的字典,然后用空字符串替换引号。

标签: python json python-3.x string yaml


【解决方案1】:

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': '困难'}}}

【讨论】:

  • 我收到错误:yaml.scanner.ScannerError: while scanning for the next token found character '\t' that cannot start any token 所以字符串似乎是制表符缩进。
  • @AlfredBalle 然后在调用yaml.load之前用几个空格替换制表符
  • @L3viathan,您在键和值之间有制表符吗?例如hello:\tworld,如果是这样,您必须先以某种方式转换输入。输入来自哪里?改变它的输出可能是最简单的。
  • 用空格替换制表符可以使东西正常工作,但并不完全。请参阅上面的更新问题。
  • 为最终问题添加了更多上下文。
【解决方案2】:
import yaml  # pip install pyyaml
import json

yaml_text = '''
header:
    hello: world
    world: hello
    this:
        is: difficult
'''
temp_dict = yaml.load(yaml_text)
json_text = json.dumps(temp_dict)

我认为您可能希望将其转换为类似 json 的字符串。上述解决方案适用于我的机器,Python 版本 3.7.6 和 PyYaml 版本 5.3。

【讨论】:

  • OP不用改成str,json就可以了。
猜你喜欢
  • 1970-01-01
  • 2020-02-15
  • 2012-02-13
  • 2013-08-17
  • 2013-09-21
  • 1970-01-01
  • 2021-01-01
  • 2015-11-21
  • 2021-09-07
相关资源
最近更新 更多