栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将“ true”(JSON)转换为等效于Python的“ True”

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将“ true”(JSON)转换为等效于Python的“ True”

尽管Python的对象声明语法与Json语法非常相似,但它们是截然不同且不兼容的。除

True
/
true
问题外,还有其他问题(例如,Json和Python处理日期的方式非常不同,而python允许单引号和注释,而Json不允许)。

解决方案不是尝试将它们视为同一事物,而是根据需要将它们从一个转换为另一个。

Python的json库可用于解析(读取)字符串中的Json并将其转换为python对象…

data_from_api = '{"response_pre": 200, ...}'  # data_from_api should be a string containing your jsoninfo = json.loads(data_from_api)# info is now a python dictionary (or list as appropriate) representing your Json

您也可以将python对象转换为json …

info_as_json = json.dumps(info)

例:

# import the json libraryimport json# Get the Json data from the question into a variable...data_from_api = """{"response_pre": 200,  "train_number": "12229",  "position": "at Source",  "route": [    {      "no": 1, "has_arrived": false, "has_departed": false,      "scharr": "Source",      "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015",      "station": "LKO", "actdep": "22:15", "schdep": "22:15",      "actarr": "00:00", "distance": "0", "day": 0    },    {      "actdep": "23:40", "scharr": "23:38", "schdep": "23:40",      "actarr": "23:38", "no": 2, "has_departed": false,      "scharr_date": "15 Nov 2015", "has_arrived": false,      "station": "HRI", "distance": "101",      "actarr_date": "15 Nov 2015", "day": 0    }  ]}"""# Convert that data into a python object...info = json.loads(data_from_api)print(info)

第二个示例显示True / true转换是如何发生的。还请注意对引号的更改以及如何删除注释…

info = {'foo': True,  # Some insightful comment here        'bar': 'Some string'}# Print a condensed representation of the objectprint(json.dumps(info))> {"bar": "Some string", "foo": true}# Or print a formatted version which is more human readable but uses more bytesprint(json.dumps(info, indent=2))> {>   "bar": "Some string",>   "foo": true> }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614320.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号