【问题标题】:How do I load a dictionary data into JSON?如何将字典数据加载到 JSON 中?
【发布时间】:2018-11-15 22:32:59
【问题描述】:

这可能很简单。我正在玩 webhook,我的一个测试抛出了一个 JSON dict 数据,我试图将其复制/粘贴到我的终端并打印它。但是我遇到了错误。为什么?请帮忙。

json.loads({"signature": {"timestamp": "1542320326", "token": "78b89c864547e371f7d708fcde9ccf3df937ce0e296cff8683", "signature": "822ae5f14a85dc25dacfd53a7ab1d55f03529aae0e8535d29758740924fde385"}, "event-data": {"tags": ["my_tag_1", "my_tag_2"], "timestamp": 1521233123.501324, "envelope": {"sending-ip": "173.193.210.33"}, "log-level": "warn", "id": "-Agny091SquKnsrW2NEKUA", "campaigns": [], "user-variables": {"my_var_1": "Mailgun Variable #1", "my-var-2": "awesome"}, "flags": {"is-test-mode": false}, "message": {"headers": {"to": "Alice <alice@example.com>", "message-id": "20110215055645.25246.63817@biennial-dot-filings.us", "from": "Bob <bob@biennial-dot-filings.us>", "subject": "Test complained webhook"}, "attachments": [], "size": 111}, "recipient": "alice@example.com", "event": "complained"}})

Traceback(最近一次调用最后一次): 文件“”,第 1 行,在 NameError: name 'false' 未定义

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    在 Python 中,false 不是有效的类型/表达式。我想你想要的是False。你可以阅读更多here

    正如@Uku 提到的,您可以使用json.loads() 来处理这个问题。

    【讨论】:

      【解决方案2】:

      Json 不直接映射到 Python 数据结构。

      你必须改用json.loads("your string")。在 JSON 中是 false,在 Python 中我们有 False

      例如

      json.loads('{"signature": {"timestamp": "1542320326", "token": "78b89c864547e371f7d708fcde9ccf3df937ce0e296cff8683", "signature": "822ae5f14a85dc25dacfd53a7ab1d55f03529aae0e8535d29758740924fde385"}, "event-data": {"tags": ["my_tag_1", "my_tag_2"], "timestamp": 1521233123.501324, "envelope": {"sending-ip": "173.193.210.33"}, "log-level": "warn", "id": "-Agny091SquKnsrW2NEKUA", "campaigns": [], "user-variables": {"my_var_1": "Mailgun Variable #1", "my-var-2": "awesome"}, "flags": {"is-test-mode": false}, "message": {"headers": {"to": "Alice <alice@example.com>", "message-id": "20110215055645.25246.63817@biennial-dot-filings.us", "from": "Bob <bob@biennial-dot-filings.us>", "subject": "Test complained webhook"}, "attachments": [], "size": 111}, "recipient": "alice@example.com", "event": "complained"}}')
      

      【讨论】:

        【解决方案3】:

        json.loads 需要一个字符串作为其参数。为了使您复制的 JSON 对象在 Python 中成为有效的字符串文字,您需要用引号将其括起来。

        由于 JSON 字符串本身包含 " 字符,因此您必须使用 '

        json.loads('{"signature": {"timestamp": "1542320326", ... }}')
        

        【讨论】:

          猜你喜欢
          • 2021-12-01
          • 2020-06-11
          • 2015-07-07
          • 1970-01-01
          • 1970-01-01
          • 2020-12-14
          • 2019-09-04
          • 2019-10-03
          • 1970-01-01
          相关资源
          最近更新 更多