JSON (Java Script Object Notation): A lightweight data interaction format that is easier to read and write than XML, is easy to parse and generate, and JSON is a subset of JavaScript. The process of serializing and deserializing the JSON modules of Python is encoding and decoding, respectively.
- Encoding: Converts a Python object encoding into a JSON string.
- Decoding: Converts the JSON format string encoding into a Python object.
JSON provides four functions: Json.loads json.dumps json.load json.dump. Loads and dumps are used to handle strings, and load and dump are used to process the files.
- Loads: Converting JSON to other formats, strings or file-related
- Dumps: Convert other objects or formats to JSON format
- Load: Converts the contents of a file into JSON data
- Dump: Writing JSON data to a file
Program examples
1. Convert dict format to JSON string format
Import= dict (name='huangdongju', age=25,message='something ')print (a) print = Json.dumps (a) Print (b)print (type (b))
Results:
2. Convert the JSON format to a dict
c = Json.loads (b)print ( type (c)) print ( c)print (c[' name '])
Results:
3. Write the JSON to the file
" " {"A": 1, "B": 2, "C": 3} " " With open ('a.txt','w') as F: Json.dump ( JSONDATA,F)
Results:
4. Converting from a file to a JSON format
With open ('a.txt','r') as fr: = json.load ( FR) print ( m)print (Type (m))
Results:
JSON module for Python