SoFunction
Updated on 2024-11-10

Common Uses of JSON in Python (,,,)

Definition of JSON

  • JSON refers to JavaScript Object Notation.
  • JSON is a lightweight textual data exchange format
  • JSON is language independent
  • JSON is self-descriptive and easier to understand

Commonly used methods

  • () read data from a json file
  • () Converts a str type to a dict type.
  • () Converts a dict type to str.
  • () Write the data to the file as a json datatype

Code Example:

() read data from a json file

with open('','r',encoding='utf-8') as f :
print((f))

Run results:

{'user_id': '66', 'movie_id': '357', 'rating': '5', 'time': '2009'}

() Converts a str type to a dict type.

import json
name_emb = {'user_id': '66', 'movie_id': '357', 'rating': '5', 'time': '2009'}
jsDumps = (name_emb)
jsLoads = (jsDumps)
print(name_emb)
print(jsDumps)
print(jsLoads)
print(type(name_emb))
print(type(jsDumps))
print(type(jsLoads))

Run results:

{'user_id': '66', 'movie_id': '357', 'rating': '5', 'time': '2009'}
{"user_id": "66", "movie_id": "357", "rating": "5", "time": "2009"}
{'user_id': '66', 'movie_id': '357', 'rating': '5', 'time': '2009'}
<class 'dict'>
<class 'str'>
<class 'dict'>

() will be dict type of data into str, if directly will be dict type of data written into the json file will occur error, so in the data will be written when you need to use the function.

import json
name_emb = {'user_id': '66', 'movie_id': '357', 'rating': '5', 'time': '2009'}
jsObj = (name_emb)
print(name_emb)
print(jsObj)
print(type(name_emb))
print(type(jsObj))

Run results:

{'user_id': '66', 'movie_id': '357', 'rating': '5', 'time': '2009'}
{"user_id": "66", "movie_id": "357", "rating": "5", "time": "2009"}
<class 'dict'>
<class 'str'>

() Write the data to the file as a json datatype

import json
name = input("Overcoming the Epidemic")
filename = ''
with open(filename, 'w') as f:
    (name, f)
    print("Go China," + name + "!")

Run results:

Go China, beat the epidemic!

to this article on the common use of JSON in Python ((), (), (), (), ()) of the article on this, more related Python JSON usage content, please search for my previous posts or continue to browse the following related articles I hope that you will support me more in the future!