为什么在馈给json.dumps()的Python对象中不能使用true/false/null? [英] Why can't I use true/false/null in a Python object fed to json.dumps()?

查看:238
本文介绍了为什么在馈给json.dumps()的Python对象中不能使用true/false/null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我正在尝试解码(我认为这是正确的词)JSON,以便将python的true,false,null转换为True,False,None
  • 我知道我需要json

我关注了此主题的答案,但它并没有带给我任何帮助.

I followed this thread's answer but it didn't get me anywhere.

...

import json

raw_json = {
'a':'aa',
'b':'bb',
'c':'cc',
'd':true,
'e':false,
'f':null
}

json_dump = json.dumps(raw_json)
json_load = json.loads(json_dump)

我在做错/需要做什么?

What am I doing wrong/need to do?

另外,我来自javascript背景,因此尝试学习约定和术语一直很痛苦.在"d2"之后,在另一个线程的链接中,"u"在每个线程的前缀前面是什么?

Also, I'm coming from a javascript background so it has been a pain trying to learn the conventions and terms. What are the 'u's prepending each json key in the other thread's link following 'd2'?

推荐答案

如果您将原始JSON嵌入到字符串中,则可以将其嵌入到代码中(如果您按照良好的做法从磁盘或网络中读取数据,就是您将拥有的):

You can embed your raw JSON in code if you do so in a string (which, if you're using good practices to read data from disk or network, is what you'll have anyhow):

# similar to what you'd get from raw_json=open('in.json', 'r').read()
raw_json = '''{
'a':'aa',
'b':'bb',
'c':'cc',
'd':true,
'e':false,
'f':null
}'''

python_struct = json.loads(raw_json)
json_again = json.dumps(raw_json)

因为truefalsenull都在字符串中,所以解析器不会尝试将它们读取为有效的Python,因此json.loads()能够以它们最初编写的方式看到它们.

Because true, false and null are all inside of the string, the parser doesn't try to read them as valid Python, so json.loads() is able to see them as they were originally written.

这篇关于为什么在馈给json.dumps()的Python对象中不能使用true/false/null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆