簡體   English   中英

將“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值。 我有點卡在這里。

盡管 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, ...}'
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
> }

您還可以使用該值對布爾值進行強制轉換。 例如,假設您的數據名為“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

這有點像hackey,但它有效。

不要對答案進行eval ,而是使用json模塊。

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

可以將 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}

我想再添加一件對正在閱讀文件的人有用的東西

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

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

data_json = json.loads(data)

json.loads 無法解析 python 布爾類型(假,真)。 Json 想要小寫字母 false,true

我的解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM