Review the json data in Python section 8

catalogue

JSON data learning

1. Data exchange

2.json syntax:

1). What is json?

2).json library functions:

3). Differences between functions:

4). Json to simulate the following databases, text documents as databases:

JSON data learning

1. Data exchange


How can the data of the website background code be transferred to the front-end web page?

Answer: through the database

How to realize data transmission for programs in different language platforms?

A: you can set an intermediate format json, which can be converted by java and python.

2.json syntax:

 1). What is json?

JSON is a syntax for storing and exchanging data. JSON (JavaScript Object Notation) was originally written in JavaScript Object Notation, but then it became a common format and was adopted by many languages, including Python.

Json uses key value pairs to represent a business object (similar to a dictionary).

{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"...} Multiple business object usage lists [] contain: [{...}, {...}, {...}, {...}, {...},...]

import json5. This is the version of json5

2).json library functions:

methodeffect
json.dumps()Encode python objects into Json strings
json.loads()Decode Json string into python object
json.dump()Convert the objects in python into json and store them in a file
json.load()Convert the format of json in the file into python object and extract it

3). Differences between dumps() and dump() and between loads() and load() functions:

dumps () and dump () are converted into json objects. The former generates strings and the latter generates character streams (text documents).

loads () is for memory objects and load () is for files. Both convert string s to dict.

For details, please see the link at the end (boss's summary).

Here is the usage of dumps() and loads():

#1. Convert JSON to python (convert to dictionary or list nested Dictionary)
jsonData='{"name": "zhangsan" , "age":18,"hobby" : "play"}'
pythonData=json5.loads(jsonData)   #load method
print(pythonData)

The result is:

{'name': 'zhangsan', 'age': 18, 'hobby': 'play'}
#ensure_ascii=True: output the ASCL code by default. If this is set to False, you can output Chinese.
pdata='{"name":"zzz","play":"run"}'
jsond=json5.dumps(pdata,ensure_ascii=False)
print(jsond,type(pdata))

The result is:

"{\"name\":\"zzz\",\"play\":\"run\"}" <class 'str'>

 

4). Json to simulate the following databases, text documents as databases:

First write data to the text document:

#Write data
with open (r"user.txt","w") as f:
    users='[{"uname": "zhangsan", "upwd": "123"}, {"uname": "lisi", "upwd": "123"}, ' \
          '{"uname": "wangwu", "upwd": "123"}, {"uname": "Dabao", "upwd": "234"}]'
    f.write(users)

Read the file and realize a login:

import json5
def readd():
    with open(r"user.txt","r") as f:
        jsond=f.read()
    userlist=json5.loads(jsond)
    return userlist
def login():
    msg="fail"
    name=input("Please enter the user name:")
    password=input("Please input a password:")
    userlist=readd()
    for user in userlist:
        if name==user['uname'] and  password ==user['upwd']:
            msg="success"
            print("Congratulations on your successful login")
    if msg=="fail" :
        print("Login failed")
    return msg
if __name__=='__main__':
    login()

       

It is more complete than the previous one (reading, writing and other operations, when reviewed) and has not been modified into the text document.

import json5

#Read data
def readd():
    with open(r"user.txt","r") as f:
        jsond=f.read()
    userlist=json5.loads(jsond)
    return userlist
#Write data (modify)
def writedata(xgname):
    userlist = readd()
    for user in userlist:
        if xgname== user['uname']:
            print(user)
            user["upwd"]=input("Please enter the password you want to change:")
            print(userlist)
        else:
            pass
           
def login():
    msg = "fail"
    name = input("Please enter the user name:")
    password = input("Please input a password:")
    userlist = readd()
    for user in userlist:
        if name == user['uname'] and password == user['upwd']:
            msg = "success"
            print("Congratulations on your successful login")
    if msg == "fail":
        print("Login failed")
    return msg,name

def main1():
    choice1=int(input("0 For login, 1 for creating a new user,Any other key is exit:"))
    if choice1 ==0:
        msg,name=login()
        if msg=="success":
            print("Start your use")
            choice2 = int(input("If you want to change your password, press 1:"))
            if choice2==1:
                writedata(name)
    elif choice1==1:
        reg()
    else:
        exit()
def reg():
    name=input("Please enter a new user:")
    password=input("Please input a password:")
    newuser={"uname":name,"upwd":password}
    userlist=readd()
    userlist.append(newuser)
    print(userlist)
if __name__=='__main__':
    main1()

Reference resources: (53 messages) JSON usage of python -- Usage of various parameters of dumps (detailed)_ Blog of monkey who likes strawberry cake - CSDN blog_ json.dump parameter

Tags: Python Pycharm

Posted by SwarleyAUS on Fri, 15 Apr 2022 00:33:08 +0930