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

2024-05-14 17:55:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的Train status 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值。 我有点困在这里了。


Tags: nojsonfalsesourcedatenovdistancehas
2条回答

不要对答案执行eval,而是使用^{}模块。

尽管Python的对象声明语法非常类似于Json语法,但它们是不同的和不兼容的。除了True/true问题之外,还有其他问题(例如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

您也可以将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...
info = json.loads(data_from_api)
print(info)

第二个例子展示了真/真转换是如何发生的。还请注意对引号的更改,以及如何删除注释。。。

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

相关问题 更多 >

    热门问题