如何将字典数据加载到JSON中?

2024-05-16 22:38:49 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能很简单。我在玩webhooks,我的一个测试抛出了一个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"}})

回溯(最近一次呼叫): 文件“”,第1行,在 NameError:未定义名称“false”


Tags: comeventidfalsemessageexamplevarmy
3条回答

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

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

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

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"}}')

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

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

相关问题 更多 >