Jar*_*win 27 python json dictionary boolean
我最近使用的Train状态API (has_arrived, has_departed)
在JSON对象中添加了两个额外的键值对,这导致我的脚本崩溃.
这是字典:
{
"response_code": 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
}
]
}
Run Code Online (Sandbox Code Playgroud)
毫不奇怪,我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'false' is not defined
Run Code Online (Sandbox Code Playgroud)
如果我没有弄错,我认为这是因为JSON响应中的布尔值是false
/ true
而Python识别False
/ True
.它有什么办法吗?
PS:我尝试将JSON响应转换has_arrived
为字符串,然后将其转换回布尔值,但发现True
如果字符串中有任何字符,我将始终获得一个值.我有点被困在这里.
Bas*_*sic 31
尽管Python的对象声明语法与JSON语法非常相似,但它们是截然不同且不兼容的.除了True
/ true
issue之外,还有其他问题(例如Json和Python处理日期的方式非常不同,而python允许注释而Json没有).
解决方案是从一个转换为另一个.
Python的json库可用于在字符串中解析(读取)Json并将其转换为python对象...
data_from_api = '{...}' # data_from_api should be a string containing your json
info = json.loads(data_from_api)
# info is now a python dictionary (or list as appropriate) representing your Json
Run Code Online (Sandbox Code Playgroud)
你也可以将python对象转换为json ...
info_as_json = json.dumps(info)
Run Code Online (Sandbox Code Playgroud)
例:
# Import the json library
import json
# Get the Json data from the question into a variable...
data_from_api = """{
"response_code": 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)
Run Code Online (Sandbox Code Playgroud)
第二个例子展示了True/true转换的发生方式.另请注意引用的更改以及如何删除注释...
info = {'foo': True, # Some insightful comment here
'bar': 'Some string'}
# Print a condensed representation of the object
print(json.dumps(info))
# Or print a formatted version which is more human readable but uses more bytes
print(json.dumps(info, indent=2))
Run Code Online (Sandbox Code Playgroud)
输出:
{"bar": "Some string", "foo": true}
{
"bar": "Some string",
"foo": true
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用该值对布尔值进行强制转换。例如,假设您的数据名为“json_data”:
value = json_data.get('route')[0].get('has_arrived') # this will pull "false" into *value
boolean_value = bool(value == 'true') # resulting in False being loaded into *boolean_value
Run Code Online (Sandbox Code Playgroud)
这有点像hackey,但它有效。
可以利用 Python 的布尔值来表示 int、str、list 等。
例如:
bool(1) # True
bool(0) # False
bool("a") # True
bool("") # False
bool([1]) # True
bool([]) # False
Run Code Online (Sandbox Code Playgroud)
在 Json 文件中,您可以设置
"has_arrived": 0,
Run Code Online (Sandbox Code Playgroud)
然后在你的Python代码中
if data["has_arrived"]:
arrived()
else:
not_arrived()
Run Code Online (Sandbox Code Playgroud)
这里的问题是不要混淆代表 False 的 0 和代表其值的 0。
归档时间: |
|
查看次数: |
42190 次 |
最近记录: |