将 "true" (JSON) 转换为 Python 等价物 "True"
Converting "true" (JSON) to Python equivalent "True"
火车状态 API 我最近在 JSON 对象中添加了两个额外的键值对 (has_arrived, has_departed)
,这导致我的脚本崩溃。
这是字典:
{
"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
}
]
}
毫不奇怪,我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'false' is not defined
如果我没记错的话,我认为这是因为 JSON 响应中的布尔值是 false
/true
而 Python 识别 False
/True
。
有什么解决办法吗?
PS:我尝试将 has_arrived
的 JSON 响应转换为字符串,然后将其转换回布尔值,结果发现我总是会得到一个True
值(如果字符串中有任何字符)。
我有点卡在这里了。
不要对答案做 eval
,而是使用 json
模块。
尽管 Python 的对象声明语法与 Json 语法非常相似,但它们截然不同且不兼容。除了 True
/true
问题,还有其他问题(例如 Json 和 Python 处理日期的方式非常不同,而 python 允许单引号和注释而 Json 没有)。
与其尝试将它们视为同一事物,不如根据需要从一种转换为另一种。
Python的原生json库可用于解析(读取)字符串中的Json并将其转换为python对象,而你已经安装了...
# Import the library
import json
# Define a string of json data
data_from_api = '{"response_code": 200, ...}'
data = 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 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...
data = json.loads(data_from_api)
print(data)
第二个示例显示了 True/true 转换是如何发生的。另请注意报价的更改以及评论的删除方式...
info = {'foo': True, # Some insightful comment here
'bar': 'Some string'}
# Print a condensed representation of the object
print(json.dumps(info))
> {"bar": "Some string", "foo": true}
# Or print a formatted version which is more human readable but uses more bytes
print(json.dumps(info, indent=2))
> {
> "bar": "Some string",
> "foo": true
> }
{ "value": False } 或 { "key": false } 不是有效的 json
https://jsonlint.com/
我想再添加一件对从文件中读取的人有用的东西。
with open('/Users/mohammed/Desktop/working_create_order.json')as jsonfile:
data = json.dumps(jsonfile.read())
然后按照上面接受的回答即
data_json = json.loads(data)
json.loads 无法解析 pythons 布尔类型(False,True)。 Json 想有小写字母 false, true
我的解决方案:
python_json_string.replace(": 真,", ": 真,").replace(": 假,", ": 假,")
您还可以将值转换为布尔值。例如,假设您的数据名为 "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
这有点像 hackkey,但它确实有效。
可以将 Python 的布尔值用于 int、str、list 等
例如:
bool(1) # True
bool(0) # False
bool("a") # True
bool("") # False
bool([1]) # True
bool([]) # False
在Json文件中,可以设置
"has_arrived": 0,
然后在你的Python代码中
if data["has_arrived"]:
arrived()
else:
not_arrived()
这里的问题是不要混淆 0 表示 False 和 0 表示它的值。
"""
String to Dict (Json): json.loads(jstr)
Note: in String , shown true, in Dict shown True
Dict(Json) to String: json.dumps(jobj)
"""
>>> jobj = {'test': True}
>>> jstr = json.dumps(jobj)
>>> jobj
{'test': True}
>>> jstr
'{"test": true}'
>>> json.loads(jstr)
{'test': True}
火车状态 API 我最近在 JSON 对象中添加了两个额外的键值对 (has_arrived, has_departed)
,这导致我的脚本崩溃。
这是字典:
{
"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
}
]
}
毫不奇怪,我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'false' is not defined
如果我没记错的话,我认为这是因为 JSON 响应中的布尔值是 false
/true
而 Python 识别 False
/True
。
有什么解决办法吗?
PS:我尝试将 has_arrived
的 JSON 响应转换为字符串,然后将其转换回布尔值,结果发现我总是会得到一个True
值(如果字符串中有任何字符)。
我有点卡在这里了。
不要对答案做 eval
,而是使用 json
模块。
尽管 Python 的对象声明语法与 Json 语法非常相似,但它们截然不同且不兼容。除了 True
/true
问题,还有其他问题(例如 Json 和 Python 处理日期的方式非常不同,而 python 允许单引号和注释而 Json 没有)。
与其尝试将它们视为同一事物,不如根据需要从一种转换为另一种。
Python的原生json库可用于解析(读取)字符串中的Json并将其转换为python对象,而你已经安装了...
# Import the library
import json
# Define a string of json data
data_from_api = '{"response_code": 200, ...}'
data = 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 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...
data = json.loads(data_from_api)
print(data)
第二个示例显示了 True/true 转换是如何发生的。另请注意报价的更改以及评论的删除方式...
info = {'foo': True, # Some insightful comment here
'bar': 'Some string'}
# Print a condensed representation of the object
print(json.dumps(info))
> {"bar": "Some string", "foo": true}
# Or print a formatted version which is more human readable but uses more bytes
print(json.dumps(info, indent=2))
> {
> "bar": "Some string",
> "foo": true
> }
{ "value": False } 或 { "key": false } 不是有效的 json https://jsonlint.com/
我想再添加一件对从文件中读取的人有用的东西。
with open('/Users/mohammed/Desktop/working_create_order.json')as jsonfile:
data = json.dumps(jsonfile.read())
然后按照上面接受的回答即
data_json = json.loads(data)
json.loads 无法解析 pythons 布尔类型(False,True)。 Json 想有小写字母 false, true
我的解决方案:
python_json_string.replace(": 真,", ": 真,").replace(": 假,", ": 假,")
您还可以将值转换为布尔值。例如,假设您的数据名为 "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
这有点像 hackkey,但它确实有效。
可以将 Python 的布尔值用于 int、str、list 等
例如:
bool(1) # True
bool(0) # False
bool("a") # True
bool("") # False
bool([1]) # True
bool([]) # False
在Json文件中,可以设置
"has_arrived": 0,
然后在你的Python代码中
if data["has_arrived"]:
arrived()
else:
not_arrived()
这里的问题是不要混淆 0 表示 False 和 0 表示它的值。
"""
String to Dict (Json): json.loads(jstr)
Note: in String , shown true, in Dict shown True
Dict(Json) to String: json.dumps(jobj)
"""
>>> jobj = {'test': True}
>>> jstr = json.dumps(jobj)
>>> jobj
{'test': True}
>>> jstr
'{"test": true}'
>>> json.loads(jstr)
{'test': True}