Happy journey of simple Python: JSON topic of Python basic syntax

Defonds 2020-11-13 04:52:42
happy journey simple python json


1. analysis JSON String example

To put JSON The string resolves to a Python object , You can use Python The built-in json library .json In the bag loads() Function to parse JSON strand .

import json
pythonObj = json.loads(jsonStr)

among ,jsonStr Is a containing JSON String of data , and json.loads() Will return a Python object . be based on JSON String data structure , return Python The data type of the object will be list or dictionary .

1.1. analysis JSON String is Python Dictionaries

Next, we create an include JSON String of data , And then use json.loads() Function to parse it .

# Parse JSON String to Python Dictionary
import json
jsonstr = '{"name":"Tesla", "age":2, "city":"New York"}'
pythonOjb = json.loads(jsonstr)
print(type(pythonOjb))
print(pythonOjb)
name = pythonOjb["name"]
print(name)

Execution and output :
 analysis JSON String is Python Dictionaries .png
In this example JSON A string is a single element that contains multiple key value pairs . therefore loads() The function should JSON The data type obtained from string parsing is Dictionary .

1.2. analysis JSON String is Python list

Next let's look at another set of elements with multiple key value pairs JSON character string , We use the same json.loads() Function to parse it .

# Parse JSON String to Python List
import json
jsonStr = '[{"name":"Tesla", "age":2, "city":"New York"}, {"name":"Jim", "age":3, "city":"Boston"}]'
pythonObj = json.loads(jsonStr)
print(type(pythonObj))
print(pythonObj)
print(type(pythonObj[0]))
print(pythonObj[0])
city = pythonObj[1]["city"]
print(city)

Execution and output :
 analysis JSON String is Python list .jpg
In this example JSON String contains more than one set of elements . Therefore, from loads() The data type returned by function parsing is a list , The data type of the elements in the list is Dictionary .

2. How to integrate Python Class object to JSON character string ?

You have to put one Python Class object to JSON character string , Or save the properties of the class object as JSON character string , Use json.dumps() Method .

jsonStr = json.dumps(myobject.__dict__)

among ,

  • json Module name .
  • dumps It's about Python Object to JSON String method . She will return to a JSON character string .
  • myobject yes Python Class object ,myobject.dict be used for Get the dictionary version of the object properties .

2.1. transformation Python Class object is JSON character string

In the next example , We define a Python class , Then I create an object of this class , Finally, the attribute is transformed into a JSON character string .

# Convert Python Class Object to JSON string
import json
class Laptop:
name = 'My Laptop'
processor = 'Intel Core'
laptop1 = Laptop()
laptop1.name = 'Dell Alienware'
laptop1.processor = 'Intel Core i7'
jsonStr = json.dumps(laptop1.__dict__)
print(jsonStr)

Execution and output :
 transformation Python Class object is JSON character string .png
You can see , Attribute names have been converted to JSON And the property value is converted to JSON Value .

2.2. take Python The properties of class objects are converted to JSON character string

In the following example , We defined a string with different data types 、 Of integer floating-point properties Python class , Then I create an object of this class , Then convert the properties of the objects of this class to JSON strand .

# Convert Properties of Python Class Object to JSON string
import json
class Laptop:
def __init__(self, name, processor, hdd, ram, cost):
self.name = name
self.processor = processor
self.hdd = hdd
self.ram = ram
self.cost = cost
laptop1 = Laptop('Dell Alienware', 'Intel Core i7', 512, 8, 2500.00)
jsonStr = json.dumps(laptop1.__dict__)
print(jsonStr)

Execution and output :
 take Python The properties of class objects are converted to JSON character string .png

3. Python Tuple to JSON Array

To put Python Tuple to JSON Array , Pass a tuple as an argument to a method json.dumps() Method .

jsonStr = json.dumps(mytuple)

3.1. transformation Python The tuple is JSON character string

In the next example , We create a tuple and convert it to a JSON character string .

# Convert Python Tuple to JSON String
import json
mytupe = ("python", "json", "mysql")
jsonStr = json.dumps(mytupe)
print(jsonStr)

Execution and output :
 transformation Python The tuple is JSON character string .png

3.2. Convert tuples containing elements of different data types to JSON character string

Next, we create a tuple of elements of different data types , And then convert it to a JSON character string . after , We should JSON String to parse and access its elements .

# Convert Python Tuple with Different Datatypes to JSON String
import json
mytupe = ("python", "json", 22, 23.04)
jsonStr = json.dumps(mytupe)
print(type(jsonStr))
print(jsonStr)
jsonArr = json.loads(jsonStr)
print(type(jsonArr))
print(jsonArr[2])

Execution and output :
 Convert tuples containing elements of different data types to JSON character string .png

Reference material

版权声明
本文为[Defonds]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database