在深入探討這個話題之前,讓我們先來看一下什麼是字元串,什麼是 JSON?
字元串:是用逗號「」表示的字元序列。它們是不可變的,這意味著一旦聲明就不能更改。
JSON: 代表「JavaScript 對象符號」,JSON 文件由人類容易閱讀的文本組成,並以屬性值對的形式存在。
JSON 文件的擴展名是」。json “
讓我們看一下 Python 中將字元串轉換為 json 的第一種方法。
下面的程序說明了同樣的情況。
# converting string to json
import json
# initialize the json object
i_string = {'C_code': 1, 'C++_code' : 26,
'Java_code' : 17, 'Python_code' : 28}
# printing initial json
i_string = json.dumps(i_string)
print ("The declared dictionary is ", i_string)
print ("It's type is ", type(i_string))
# converting string to json
res_dictionary = json.loads(i_string)
# printing the final result
print ("The resultant dictionary is ", str(res_dictionary))
print ("The type of resultant dictionary is", type(res_dictionary))
輸出:
The declared dictionary is {'C_code': 1, 'C++_code' : 26,
'Java_code' : 17, 'Python_code' : 28}
It's type is <class 'str'>
The resultant dictionary is {'C_code': 1, 'C++_code' : 26,
'Java_code' : 17, 'Python_code' : 28}
The type of resultant dictionary is <class 'dict'>
說明:
是時候看到解釋了,這樣我們的邏輯就變得清晰了-
- 由於這裡的目標是將字元串轉換為 json 文件,我們將首先導入 json 模塊。
- 下一步是初始化 json 對象,在該對象中,我們將主題名稱作為鍵,然後指定它們對應的值。
- 之後,我們使用轉儲()將 Python 對象轉換為 json 字元串。
- 最後,我們將使用 loads() 解析一個 JSON 字元串並將其轉換為字典。
使用 eval()
# converting string to json
import json
# initialize the json object
i_string = """ {'C_code': 1, 'C++_code' : 26,
'Java_code' : 17, 'Python_code' : 28}
"""
# printing initial json
print ("The declared dictionary is ", i_string)
print ("Its type is ", type(i_string))
# converting string to json
res_dictionary = eval(i_string)
# printing the final result
print ("The resultant dictionary is ", str(res_dictionary))
print ("The type of resultant dictionary is ", type(res_dictionary))
輸出:
The declared dictionary is {'C_code': 1, 'C++_code' : 26,
'Java_code' : 17, 'Python_code' : 28}
Its type is <class 'str'>
The resultant dictionary is {'C_code': 1, 'C++_code': 26, 'Java_code': 17, 'Python_code': 28}
The type of resultant dictionary is <class 'dict'>
說明:
讓我們了解一下我們在上面的程序中做了什麼。
- 由於這裡的目標是將字元串轉換為 json 文件,我們將首先導入 json 模塊。
- 下一步是初始化 json 對象,在該對象中,我們將主題名稱作為鍵,然後指定它們對應的值。
- 之後,我們使用 eval() 將一個 Python 字元串轉換為 json。
- 在執行程序時,它會顯示所需的輸出。
正在獲取值
最後,在最後一個程序中,我們將在字元串轉換為 json 後獲取值。
讓我們來看看。
import json
i_dict = '{"C_code": 1, "C++_code" : 26, "Java_code":17, "Python_code":28}'
res = json.loads(i_dict)
print(res["C_code"])
print(res["Java_code"])
輸出:
1
17
我們可以在輸出中觀察到以下情況-
- 我們已經使用 json.loads()將字元串轉換為 json。
- 在此之後,我們使用鍵「C_code」和「Java_code」來獲取它們相應的值。
結論
在本教程中,我們學習了如何使用 Python 將字元串轉換為 json。
原創文章,作者:DSD9P,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/129902.html