Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does python store json data

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article focuses on "how python stores json data". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how python stores json data.

First we need to introduce the json module: import json

Here we simulate a common. We ask the user to enter the user name and password, and prompt the user to enter the password again after the password is entered to confirm his input. If the password is the same twice, then we write the user name and password to the file in json format, otherwise the user is prompted to enter the password again.

Name = input ("please enter your name:") password = input ("please enter your password:") confirm_password = input ("confirm your password:") while password! = confirm_password: print ("input password inconsistencies,please try again") password = input ("please enter your password:") confirm_password = input ("confirm your password:")

Ok, we can get the user name and password through user input, and then we need to save both to the file in json format.

First, we convert our input to a json object:

User_info = json.dumps ({'username': name,' password': password}, sort_keys=True, indent=4, ensure_ascii=False) print (user_info)

Here we use the json.dumps function, which encodes the Python object into a JSON string.

Syntax:

Def dumps (obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, * * kw) Inferred type: (obj: Any, Any, skipkeys: bool, ensure_ascii: bool, check_circular: bool, allow_nan: bool, cls: Any, indent: Any, separators: Any, default: Any, sort_keys: bool, kw: Dict [Dict, str])-> str

Where sort_keys is used to specify whether objects in json format are sorted by the name of key, and the indent parameter specifies the number of indented spaces.

The final input format is as follows:

{"password": "us", "username": "us"}

So next we write the json object to the file:

With open ('user_info.json',' wicked, encoding='utf-8') as json_file: json.dump (user_info, json_file, ensure_ascii=False) print ("write json file success!")

Here we need to learn a function json.dump:

Def dump (obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, * * kw) Inferred type: (obj: Any, fp: {write}, Any, skipkeys: bool, ensure_ascii: bool, check_circular: bool, allow_nan: bool, cls: Any, indent: Any, separators: Any, default: Any, sort_keys: sort_keys, bool: bool [kw, kw])-> kw

This function has two parameters that we have to fill in: obj (the data we want to store) and fp (the file handle, that is, we want to store in that file).

The parameter ensure_ascii=False deals with scenes that we want to contain Chinese in the json object.

If ensure_ascii is false, then the strings written to fp can contain non-ASCII characters if they appear in strings contained in obj. Otherwise, all such characters are escaped in JSON strings.

If ensure_ascii=False is not specified, then when our data contains Chinese:

{"username": "zhangu4e09", "password": "ddd"}

There will be a display like the above.

We run the program and enter the user name and password in turn:

Please enter your name:usplease enter your password:usconfirm your password:us {"username": "us", "password": "us"} write json file qualified process finished with exit code 0

Next we need to learn how to read content in json format.

With open ('user_info.json',' ritual, encoding='utf-8') as json_file: data = json.load (json_file) print (data)

You need to use the json.load function to read json data:

Def load (fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, * * kw) Inferred type: (fp: {read}, Any, cls: Any, object_hook: Any, parse_float: Any, parse_int: Any, parse_constant: Any, object_pairs_hook: Any, kw: Dict [str, Any])-> Any

Here we need to provide a parameter fp, that is, the file handle we want to operate on.

Program running output:

{"username": "us", "password": "us"}

We can print out what type of json.load returns:

Print (type (data))

Output:

So, this is a string. Why is that? Shouldn't you return the object corresponding to python?

In the above code, we called before writing to the file:

User_info = json.dumps ({'username': name,' password': password}, ensure_ascii=False)

Remember, this line of code returns a json string, so in the above example, we need to use json.loads to deserialize the python object. Please note that the above example is to demonstrate the relevant usage of json.loads, using the following:

Data = json.loads (data) print (type (data)) print (data ['username'])

Without this line of code, data = json.load (json_file) returns the data structure that we organized, and if it is still in the format {'username': name,' password': password}, the return is a dictionary object.

Let's take a look at it through a list:

Data = [with open ('user_info.json', 'wicked, encoding='utf-8') as json_file: json.dump (data, json_file, ensure_ascii=False) with open (' user_info.json', 'ritual, encoding='utf-8') as json_file: data = json.load (json_file) print (type (data)) print (data)

Run the program:

[1, 2, 3, 4, 5]

Add: Python creates and saves json files to support data updating and saving

Let's just look at the code ~ import jsonclass Params (): "Class that loads hyperparameters from a json file. Example: ````params = Params (json_path) print (params.learning_rate) params.learning_rate = 0.5 # change the value of learning_rate in params ```"" def _ _ init__ (self) Json_path): with open (json_path) as f: params = json.load (f) # convert json format data to dictionary self.__dict__.update (params) def save (self, json_path): with open (json_path,'w') as f: json.dump (self.__dict__, f Indent=4) # indent indent level for beautiful printing def update (self Json_path): "" Loads parameters from json file "with open (json_path) as f: params = json.load (f) self.__dict__.update (params) @ property # Python built-in @ property decorator is the def dict (self) responsible for turning a method into a property call:"Gives dict-like access to Params instance By `params.dict ['learning_rate'] "" return self.__dict__if _ _ name__ = =' _ main__': parameters = {"SEED": 1 "dataset": "Omniglot", "meta_lr": 1e-3, "num_episodes": 5000, "num_classes": 5, "num_samples": 1, "num_query": 10, "num_steps": "num_inner_tasks": 8, "num_train_updates": 1, "num_eval_updates": 1, "save_summary_steps": 100, "num_workers": 1} json_str = json.dumps (parameters, indent=4) with open ('params.json' 'w') as f: # create a params.json file f.write (json_str) # write json_str to the file params = Params ('params.json') params.SEED = 2 # modify the data in json params.save (' params.json') # Save the modified data here I believe you have a deeper understanding of "how python stores json data". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report