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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33722662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:50:34  来源:igfitidea点击:

Converting "true" (JSON) to Python equivalent "True"

pythonjsondictionaryboolean

提问by Jarwin

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.

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

Here's the dictionary:

这是字典:

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

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

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

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

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

采纳答案by Basic

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

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

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

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

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

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

You can convert python objects to json too...

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

info_as_json = json.dumps(info)

Example:

例子:

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

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

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

回答by memoselyk

Instead of doing evalon the answer, use the jsonmodule.

eval使用json模块,而不是做答案。

回答by Fabián Fuentealba

{ "value": False } or { "key": false } is not a valid json https://jsonlint.com/

{ "value": False } 或 { "key": false } 不是有效的 json https://jsonlint.com/

回答by mohammed_ayaz

I would like to add one more thing that would work for people who are reading from a file.

我想再添加一件对正在阅读文件的人有用的东西

with open('/Users/mohammed/Desktop/working_create_order.json')as jsonfile:
            data = json.dumps(jsonfile.read())

Then follow the above acceptedanswer i.e.

然后按照上面接受的答案即

data_json = json.loads(data)

回答by Willi Schmidt

json.loads cant parse the pythons boolean type (False, True). Json wants to have small letters false, true

json.loads 无法解析 python 布尔类型(假,真)。Json 想要小写字母 false,true

my solution:

我的解决方案:

python_json_string.replace(": True,", ": true,").replace(": False,", ": false,")

python_json_string.replace(": True,", ": true,").replace(": False,", ": false,")

回答by g_sexton

You can also do a cast to boolean with the value. For example, assuming that your data is called "json_data":

您还可以使用该值对布尔值进行强制转换。例如,假设您的数据名为“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

It's kind of hackey, but it works.

这有点像hackey,但它有效。