当前位置:网站首页>JSON file storage
JSON file storage
2022-07-28 08:59:00 【W_ chuanqi】
Personal profile
Author's brief introduction : Hello everyone , I am a W_chuanqi, A programming enthusiast
Personal home page :W_chaunqi
Stand by me : give the thumbs-up + Collection ️+ Leaving a message.
May you and I share :“ If you are in the mire , The heart is also in the mire , Then all eyes are muddy ; If you are in the mire , And I miss Kun Peng , Then you can see 90000 miles of heaven and earth .”

List of articles
JSON File store
JSON, Its full name is Java Script Object Notation, That is to say JavaScript Object tag , Represents data through a combination of objects and arrays , Although the structure is simple, the degree of structure is very high , Is a lightweight data exchange format .
Now let's learn how to use Python Store data as JSON file .
1. Objects and arrays
stay JavaScript In language , Everything is the object , Therefore, any supported data type can pass JSON Express , For example, substring 、 Numbers 、 object 、 Array etc. . Among them, object and array are two special and commonly used types , Let's briefly introduce these two .
The object is JavaScript Middle means to use curly brackets {} Surrounded content , The data structure is {key1:value1,key2:value2,…} This key value pair structure . In an object-oriented language ,key Represents the properties of an object 、value Represents the value corresponding to the attribute , The former can be represented by integers and strings , The latter can be of any type .
Array in JavaScript Chinese means to use square brackets [] Surrounded content , The data structure is [“java”,“javascript”,“vb”,…】 This index structure . stay JavaScript in , Array is a special data type , Because it can also use key value pair structures like objects , But the index structure is used more . Again , Its value can be of any type .
therefore , One JSON Objects can be written in the following form :
[{
"name":"Bob",
"gender":"male",
"birthday":"1992-10-18"
},
{
"name":"Selina",
"gender":"female",
"birthday":"1995-11-16"
}]
from [] The enclosed content is equivalent to an array , Each element in the array can be of any type , The elements in this instance are objects , from {} Surround .
JSON It can be freely combined from the above two forms , It can be nested infinite times , And the structure is clear , It is an excellent way to realize data exchange .
2. Read JSON
Python It provides us with a simple and easy to use JSON library , Used to implement JSON Read and write operation of the file , We can call JSON In the library loads Methods will JSON Text string to JSON object . actually ,JSON Object is Python Nesting and combination of lists and dictionaries in . In turn, , We can go through dumps Methods will JSON Object into a text string .
for example , Here's a passage JSON String of form , yes str type , We use it Python Turn it into an operational data structure , Like a list or dictionary :
import json
str = ''' [{ "name":"Bob", "gender":"male", "birthday":"1992-10-18" }, { "name":"Selina", "gender":"female", "birthday":"1995-11-16" }] '''
print(type(str))
data = json.loads(str)
print(data)
print(type(data))
The operation results are as follows :
Use here loads Method converts a string to JSON object . Because the outermost layer is brackets , So the final data type is list type .
thus , We can use the index to get the corresponding content . for example , To get the in the first element name attribute , You can use the following methods :
import json
str = ''' [{ "name":"Bob", "gender":"male", "birthday":"1992-10-18" }, { "name":"Selina", "gender":"female", "birthday":"1995-11-16" }] '''
data = json.loads(str)
print(data[0]['name'])
print(data[0].get('name'))
The output is :

Add... In brackets 0 As index , You can get the first dictionary element , Then call its key name to get the corresponding key value . There are two ways to get key values , One is to add key names in brackets , The other is to use get Method to pass in the key name . It is recommended to use get Method , In this way, even if the key name does not exist , No errors reported , But will return to None. in addition ,get Method can also pass in a second parameter ( Default value ), Examples are as follows :
import json
str = ''' [{ "name":"Bob", "gender":"male", "birthday":"1992-10-18" }, { "name":"Selina", "gender":"female", "birthday":"1995-11-16" }] '''
data = json.loads(str)
print(data[0].get('age'))
print(data[0].get('age', 25))
The operation results are as follows :

The second parameter , The value passed in will be returned . Here we try to get the age age, The key name does not exist in the original dictionary , Therefore, it will return by default None. At this time, if the second parameter is passed , The value passed in will be returned .
It is worth noting that ,JSON The data of needs to be enclosed in double quotation marks , Instead of using single quotes . For example, use the following form , There will be errors :
import json
str = ''' [{ 'name':'Bob', 'gender':'male', 'birthday':'1992-10-18' }] '''
data = json.loads(str)
The operation results are as follows :
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 3 column 5 (char 8)
It's here JSON Tips for parsing errors , The reason is that the data is surrounded by single quotation marks . Again , Please pay attention to JSON Double quotation marks are required for string representation , otherwise loads Method will fail to parse . The following implementation is from JSON Read in text , For example, there is a data.json text file , Its content is just defined JSON word Fu string , We can read out the contents of the text file first , recycling loads Methods transform it into JSON object :
import json
with open('data.json', encoding='utf-8') as file:
str = file.read()
data = json.loads(str)
print(data)
The operation results are as follows :

Here we use open Method to read a text file , The default read mode is used , The encoding is specified as utf-8, And the file operation object is assigned file. Then we call file Object's read Method reads everything in the text , The assignment is str. Then call loads Method resolution JSON character string , Convert it to JSON object .
In fact, there is a simpler way to write the above examples , You can use it directly load Method passes in the file operation object , You can also convert text into JSON object , It is written as follows :
import json
data = json. load(open('data.json', encoding='utf-8'))
print(data)
Pay attention to the use of load Method , instead of loads Method . The parameter of the former is a file operation object , The latter parameter is a JSON character string .
The operation results of these two methods are exactly the same . It's just load The method is to convert the contents of the entire file into JSON object , and loads Method can control which content to convert more flexibly . The two methods can be used in appropriate scenarios .
3. Output JSON
You can call dumps Methods will JSON Object to string . for example , Rewrite the list in the running result of the above example into the text :
Here use dumps Method , take JSON Object to string , Then call the write Method writes a string to text , The results are shown in the following figure .

in addition , If you want to save JSON Indent format of object , Can go again dumps Method indent, Represents the number of indented characters . Examples are as follows :
import json
data = [{
'name': 'Bob',
'gender': 'male',
'birthday': '1992-10-18'
}]
with open('data.json', 'w', encoding='utf-8') as file:
file.write(json.dumps(data, indent=2))
At this time, the write result is shown in the figure .

Can see , The content obtained has its own indentation , The format is clearer .
in addition , If JSON Object contains Chinese characters , What will happen ? Now before JSON Some values in the object are changed to Chinese , And still use the previous method to write it into the text :
import json
data = [{
'name': ' Zhang San ',
'gender': ' male ',
'birthday': '1992-10-18'
}]
with open('data.json', 'w', encoding='utf-8') as file:
file.write(json.dumps(data, indent=2))
The write result is shown in the figure :

You can see , The Chinese characters in the text have become Unicode character , This is obviously not what we want .
To output Chinese , You also need to specify parameters ensure_ascii by False, And specify the code of document output :
import json
data = [{
'name': ' Zhang San ',
'gender': ' male ',
'birthday': '1992-10-18'
}]
with open('data.json', 'w', encoding='utf-8') as file:
file.write(json.dumps(data, indent=2, ensure_ascii=False))
The write result at this time is shown in the figure :

Can be found , Now we can put JSON Object output is Chinese .
analogy loads And load Method ,dumps There is also a corresponding dump Method , It can directly transfer JSON All objects are written to the file , Therefore, the above writing method can also be written in the following form :
json.dump(data, open('data.json','w', encoding='utf-8'), indent=2, ensure_ascii=False)
The first parameter here is JSON object , The second parameter can be passed into the file operation object , Other indent、ensure_ascii The object remains unchanged , The results are the same .
边栏推荐
- [advanced drawing of single cell] 07. Display of KEGG enrichment results
- No one wants to tell the truth about kubernetes secret
- Go interface Foundation
- Does gbase 8s support storing relational data and object-oriented data?
- Business digitalization is running rapidly, and management digitalization urgently needs to start
- Argocd Web UI loading is slow? A trick to teach you to solve
- [cloud computing] several mistakes that enterprises need to avoid after going to the cloud
- 一年涨薪三次背后的秘密
- A new method of exposing services in kubernetes clusters
- Will sqlserver CDC 2.2 generate table locks when extracting large tables from the source
猜你喜欢

Hcip day 8
![[advanced drawing of single cell] 07. Display of KEGG enrichment results](/img/77/0a9006743734c1993785d087f957f0.png)
[advanced drawing of single cell] 07. Display of KEGG enrichment results

Source code analysis of linkedblockingqueue

Chapter 2-14 sum integer segments

NDK series (6): let's talk about the way and time to register JNI functions
![[activity registration] User Group Xi'an - empowering enterprise growth with modern data architecture](/img/92/88be42faf0451cb19067672dab69c8.jpg)
[activity registration] User Group Xi'an - empowering enterprise growth with modern data architecture

Gbase appears in Unicom cloud Tour (Sichuan Station) to professionally empower cloud ecology

说透缓存一致性与内存屏障

XMIND Zen installation tutorial
![Chapter 2-2 calculation of piecewise function [1]](/img/40/cad6bf92849624199af0fd1ba1d433.jpg)
Chapter 2-2 calculation of piecewise function [1]
随机推荐
Kubernetes cluster configuration serviceaccount
How CI framework integrates Smarty templates
解决:IndexError: index 13 is out of bounds for dimension 0 with size 13
Go interface Foundation
【单细胞高级绘图】07.KEGG富集结果展示
[advanced drawing of single cell] 07. Display of KEGG enrichment results
JS手写函数之slice函数(彻底弄懂包头不包尾)
Alibaba technology has four sides + intersection +hr, and successfully got the offer. Can't double non undergraduate students enter the big factory?
Among China's top ten national snacks, it is actually the first
我来教你如何组装一个注册中心?
Gbase 8A MPP and Galaxy Kirin (x86 version) complete deep adaptation
NDK 系列(6):说一下注册 JNI 函数的方式和时机
Flink Window&Time 原理
Different HR labels
Top all major platforms, 22 versions of interview core knowledge analysis notes, strong on the list
Review the past and know the new MySQL isolation level
kubernetes之Deployment
Overview of head pose estimation
Recycling of classes loaded by classloader
[cloud computing] several mistakes that enterprises need to avoid after going to the cloud