current position:Home>JSON and other types convert to each other in Python
JSON and other types convert to each other in Python
2022-05-15 05:35:49【A small pit of goods】
json And other types of conversions
It's often used in projects json
Format to object
object 、dict
Dictionary format, etc . Make a record here , Convenient for subsequent use, this method can quickly copy and paste .
Need to use json
package .
loads()
: takejson
Data conversion intodict
Dictionary dataload()
: Readjson
File data , Turn intodict
datadumps()
: takedict
Data conversion tojson
datadump()
: takedict
Data conversion intojson
Write the data laterjson
file
""" @Description: json And other types """
import json
import os
class JsonToOtherType:
""" @ClassName: JsonToOtherType @Description: Json Data and other data are transferred to each other loads(): take json Data conversion into dict Dictionary data load(): Read json File data , Turn into dict data dumps(): take dict Data conversion to json data dump(): take dict Data conversion into json Write the data later json file """
def __init__(self):
""" @Description: """
pass
# Set to static method
@staticmethod
def dict_to_json(dict_data:dict):
""" @Description: dict Dictionary transfer json data :param dict_data Dictionary data :return json_data return json Type data """
try:
json_data = json.dumps(dict_data)
except Exception as e:
return e
return json_data
@staticmethod
def obj_to_json(obj_data:object):
""" @Description: Object turn json data obj.__dict__: Convert objects to dict Dictionary type json.dumps(): Then convert the dictionary type to json data :param obj_data Object data """
try:
dict_data = obj_data.__dict__
# transformation dict Dictionary type
json_data = json.dumps(obj=dict_data)
except Exception as e:
return e
return json_data
@staticmethod
def json_to_dict(json_data:str):
""" @Description: json Data conversion into dict Dictionary data :param json_data json data :return dict_data return dict Dictionary data """
try:
dict_data = json.loads(s=json_data)
except Exception as e:
return e
return dict_data
@staticmethod
def json_to_obj(json_data:str,obj:object):
""" @Description: json Data conversion into obj object 1. First the json Data conversion into dict Dictionary data 2. Then convert the dictionary data into obj object :param json_data json data :param obj transformable obj object :return obj Returned object """
try:
dict_data = json.loads(s=json_data)
obj.__dict__ = dict_data
except Exception as e:
return e
return obj
@staticmethod
def dict_to_json_write_file(dict_data:dict,filepath:str,filename:str):
""" @Description: take dict Data conversion into json Write the data later json file dump(): take dict Data conversion into json Write the data later json file :param dict_data Dictionary data :param filepath File path :param filename File name """
try:
with open (os.path.join(filepath,filename),'w',encoding='utf-8') as f:
# A... Will be generated under the corresponding path filename Name file , The content of the document is dict Dictionary data is converted into json data
json.dump(dict_data,f)
except Exception as e:
return e
@staticmethod
def json_file_to_dict(filepath:str,filename:str):
""" @Description: Read json The data in the file , Convert the contents of the file into dict Dictionary data load(): Read json File data , Turn into dict data :param filepath File path :param filename File name :return dict_data Returned dictionary data """
try:
with open(os.path.join(filepath,filename),'r',encoding='utf-8') as f:
dict_data = json.load(fp=f)
except Exception as e:
return e
return dict_data
If there is a mistake , Comments or private letters are welcome to point out , thank you !
copyright notice
author[A small pit of goods],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/135/202205142240049351.html
The sidebar is recommended
- Build Python project in Jenkins, pychar output is normal and Jenkins output modulenotfounderror: no module named problem
- Interface request processing of Python webservice
- Download third-party libraries offline in Python
- Web automation in Python
- Importlib.exe in Python import_ Module import module
- Operation of OS Library in Python
- Some integration operations on Web pages in Python
- Python realizes the super fast window screenshot, automatically obtains the current active window and displays the screenshot
- Implementation of workstation monitoring system with Python socket
- Resume Automation - word 92
guess what you like
Django foundation -- 02 small project based on Database
Python drawing word cloud
Django foundation -- 02 small project based on Database
MNIST dataset classification based on Python
Design of FTP client server based on Python
Signing using RSA algorithm based on Python
Website backend of online book purchase function based on Python
Implementation of Tetris game based on Python greedy search
Django Foundation
Case: Python weather broadcast system, this is a rainy day
Random recommended
- Python development alert notification SMS alert
- How to configure Python environment library offline in FME
- Python: fastapi - beginner interface development
- Generate password based on fast token and fast token
- [Django CI system] use of json-20220509
- [Django CI system] if the front-end date is complete, it will be fully updated to the back-end; If the front-end date is incomplete, the date will not be updated to the back-end-20220510
- [Django CI system] echarts dataset standard writing - 20220509
- [Django CI system] obtain the current time, the first day and the last day of the month, etc. - 20220510
- wxPython wx. Correction of font class · Wx Font tutorial
- NCT youth programming proficiency level test python programming level 3 - simulation volume 2 (with answers)
- Design of personal simple blog system based on Django (with source code acquisition method)
- [Python Script] classify pictures according to their definition
- Wu Enda's classic ml class is fully upgraded! Update to Python implementation and add more intuitive visual teaching
- Six built-in functions called immortals in Python
- Some insights of pandas in machine learning
- Introduction to Python [preliminary knowledge] - programming idea
- Stay up late to tidy up! Pandas text processing Encyclopedia
- Python recursion to find values by dichotomy
- Open 3D Python Interface
- [true title 02 of Blue Bridge Cup] Python output natural number youth group analysis of true title of Blue Bridge Cup Python national competition
- Introduction to the differences between Python and Java
- Explain Python CONDA in detail
- The pycham downloaded by MAC reports an error as soon as it is opened. The downloaded Python interpreter is also the latest version
- From entry to mastery, python full stack engineers have personally taught Python core technology and practical combat for ten years
- Python is used to detect some problems of word frequency in English text.
- How to choose between excel, database and pandas (Python third-party library)?
- WxPython download has been reporting errors
- Pyside6 UIC and other tools cannot be found in the higher version of pyside6 (QT for Python 6). How to solve it?
- About Python Crawlers
- Successfully imported pandas, unable to use dataframe
- How to extract some keywords in the path with Python
- Python encountered a problem reading the file!
- When Python is packaged into exe, an error is reported when opening assertionerror: C: \ users \ Acer \ appdata \ local \ temp\_ MEI105682\distutils\core. pyc
- Eight practical "no code" features of Python
- Python meets SQL, so a useful Python third-party library appears
- 100 Python algorithm super detailed explanation: a hundred dollars and a hundred chickens
- [fundamentals of Python] Python code and so on
- When Python uses probit regression, the program statement is deleted by mistake, and then it appears_ raise_ linalgerror_ Unrecognized error of singular
- Python testing Nicholas theorem
- Accelerating parallel computing based on python (BL) 136