将"true"转换为"true" (JSON)与Python等效的"True" [英] Converting "true" (JSON) to Python equivalent "True"

查看:1289
本文介绍了将"true"转换为"true" (JSON)与Python等效的"True"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近使用的Train status API在JSON对象中添加了两个额外的键值对(has_arrived, has_departed),这导致我的脚本崩溃.

The Train status API I use recently added two additional key value pairs (has_arrived, has_departed) in the JSON object, which caused my script to crash.

这是字典:

{
"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
    }
  ]
}

毫不奇怪,我遇到了以下错误:

Not surprisingly, I got the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'false' is not defined

如果我没记错的话,我认为这是因为JSON响应中的布尔值是false/true,而Python可以识别False/True. 有什么办法解决吗?

If I am not mistaken, I think this is because the boolean value in the JSON response is false/true whereas Python recognizes False/True. Is there any way around it?

PS:我尝试将has_arrived的JSON响应转换为字符串,然后将其转换回布尔值,但发现如果字符串中有任何字符,我总是会得到True值. 我有点卡在这里.

PS: I tried converting the JSON response of has_arrived to string and then converting it back to a boolean value, only to find out that I'll always get a True value if there's any character in the string. I am kinda stuck here.

推荐答案

即使Python的对象声明语法与Json语法非常相似,但它们是不同的且不兼容.除了True/true问题外,还有其他问题(例如,Json和Python处理日期的方式非常不同,而python允许注释,而Json不允许).

Even though Python's object declaration syntax is very similar to Json syntax, they're distinct and incompatible. As well as the True/true issue, there are other problems (eg Json and Python handle dates very differently, and python allows comments while Json does not).

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

Instead of trying to treat them as the same thing, the solution is to convert from one to the other as needed.

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

Python's json library can be used to parse (read) the Json in a string and convert it into a python object...

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

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

You can convert python objects to json too...

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...
info = json.loads(data_from_api)
print(info)

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

And a second example showing how the True/true conversion happens. Note also the changes to quotation, and how the comment is stripped...

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))

输出:

{"bar": "Some string", "foo": true}
{
  "bar": "Some string",
  "foo": true
}

这篇关于将"true"转换为"true" (JSON)与Python等效的"True"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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