Learn Python from scratch | what is Python JSON?

Hua Weiyun 2021-04-07 12:31:05
learn python scratch python json


This article is shared from Huawei cloud community 《 Learn from scratch python | What is? Python JSON And how to achieve ?》, Original author :Yuchuan .

You know how to get from online API Transfer data or store all kinds of data to local computer ? You have immersed yourself in JSON In one way ,JSON Express Java Script Object Notation. It's a famous popular data format , Used to represent semi-structured data . Let's learn more about Python JSON.

This article will discuss the following aspects :

  • Python JSON brief introduction
  • How to be in Python Read from JSON file
  • Parsing
    • from Python Convert to JSON
    • from JSON Convert to Python
  • Panda analysis JSON
  • JSON serialize [ code ]
  • Beautiful printing
  • JSON Deserialization of [ decode ]
  • Coding demonstration

Python JSON brief introduction :

JSON representative JAVA trumpet script objectn Flotation is a way of storing information in an organized and easy way . When exchanging data between the browser and the server , The data must be in text form .

If you want to know if it is JavaScript? So the answer is "No" . It's a script of text , For storing and transmitting data in human and machine readable formats . It's a kind of reception JavaScript Inspired small lightweight data formats , Usually in text or string format .JSON Packets are almost equivalent to python Dictionaries . Now? , You must want to know .

How to be in Python Read from JSON file ?

The answer is , You must import JSON modular , This module will usually Python The data type is converted to JSON String file . It comes directly from JSON File read and write JSON Function composition .Python With built-in JSON package , And part of the standard library , So you don't have to install it .

Example :

import json

Now you know Python Medium JSON, Let's take a closer look at Parsing.

analysis :

JSON Libraries can parse from strings or files JSON . It can also put JSON Resolved to Python In a dictionary or list , vice versa . Parsing is usually divided into two stages :

  1. from JSON Convert to Python
  2. from Python Convert to JSON

Let's better understand these two stages .

from JSON Convert to Python:

You can use the following methods to JSON String conversion to Python json.loads(). :

Example :

import json
people_string = '''
{
"people":[
{
"emp_name": "John smith",
"emp_no.": "924367-567-23",
"emp_email": ["johnsmith@dummyemail.com"],
"has_license": "false"
},
{
"emp_name": "harshit kant",
"emp_number": "560-555-5153",
"emp_email": "null",
"has_license": "true"
}
]
}
'''
data = json.loads(people_string)
print(data)

Output :

As you can see from the output above , It has been printed Python Dictionaries . Let's print data types to better understand .

Example :

import json
people_string = '''
{
"people":[
{
"emp_name": "John smith",
"emp_no.": "924367-567-23",
"emp_email": ["johnsmith@dummyemail.com"],
"has_license": "false"
},
{
"emp_name": "harshit kant",
"emp_number": "560-555-5153",
"emp_email": "null",
"has_license": "true"
}
]
}
'''
data = json.loads(people_string)
print(type(data)) #prints the datatype

Output :

<class'dict'>

Now? , You are already familiar with a transformation , Let's look at another type of transformation in the second phase .

from Python Convert to JSON:

By using json.dumps(). Here's an example , Can be Python Object to JSON character string :

Example :

import json
people_string = '''
{
"people":[
{
"emp_name": "John smith",
"emp_no.": "924367-567-23",
"emp_email": ["johnsmith@dummyemail.com"],
"has_license": "false"
},
{
"emp_name": "harshit kant",
"emp_no.": "560-555-5153",
"emp_email": "null",
"has_license": "true"
}
]
}
'''
data = json.loads(people_string)
new_string = json.dumps(data)
print(new_string)

Output :

The output will be JSON String type . I am already in JSON To Python Data types are demonstrated in the transformation of , The same process will be followed to print data types .

Let's move on , have a look Pandas How to parse JSON.

Panda analysis JSON:

You can use the following steps to JSON The string resolves to pandas Dataframe:

  • The following general structure can be used to JSON The string is loaded into DataFrame in
import pandas as pd
pd.read_json(r'Path where you saved the JSON fileFile Name.json')
  • Get ready JSON character string .
  • Create one that we're using JSON file nobel_prize.json.
  • take JSON File loading to pandas DataFrame in .

The code implemented below will be my JSON File loading to DataFrame in .

import pandas as pd
import json
with open(r'C:UsersHarshit_KantDesktopnobel.prize.json') as f:
data = json.load(f)
print (data)
df = pd.DataFrame
print(df)

Output :

To move forward , Let's see how Python Serialization in JSON.

JSON serialize [ code ]:

serialize JSON It just means you're coding JSON. It will give Python data structure (ex:dict) Convert to its effective JSON object . To handle the data flow in the file ,Python Medium JSON Library usage dump() and dumps() Method , This method transforms and makes it easy to write data to a file .

The following table shows that Python Data types are converted to their respective JSON Types of tables .

Key points to remember :

dump() – Convert data to JSON file
dumps() – Convert data to JSON character string
load() – take JSON The file is converted to Python object
loads()– take JSON The object of the string is converted to Python object

Beautiful printing :

Pretty Printing Responsible for code alignment and making it human readable . Let's look at the following example , Where I pass two parameters 'sort_keys', These parameters always return Booleans True Values and 'indent' Space .

Example :

import json
people_string = '''
{
"people":[
{
"emp_name": "John smith",
"emp_no.": "924367-567-23",
"emp_email": ["johnsmith@dummyemail.com"],
"has_license": "false"
},
{
"emp_name": "harshit kant",
"emp_no.": "560-555-5153",
"emp_email": "null",
"has_license": "true"
}
]
}
'''
data = json.loads(people_string)
new_string = json.dumps(data, sort_keys=True, indent=3)
print(new_string)

Output :

Keep going Python JSON course , Let us know JSON Deserialization of .

JSON Deserialization of [Decode]:

JSON Deserialization of is the opposite of serialization , in other words , That means you're decoding JSON. It will perform the transformation by using load() and load() Method will be given JSON String conversion to Python object .

The following table shows that JSON The data type is converted to its corresponding Python Types of tables .

Keep going “ Python JSON” course . I'll show you a real-time example of serializing and deserializing at the same time from a coding perspective .

Coding demo :

In this coding demonstration , I will use the JSON Data sets , be called “ Nobel prize ” . You will learn how to pass JSON File serialization and deserialization .

Example (JSON Serialization of data sets ):

import json
with open('nobel_prize.json.html') as f:
data = json.load(f)
with open('new_nobel_prize.json.html') as f:
json.dump(data,f,indent=2)

Output :

Python Code compiled successfully , And created a new file “ new_nobel_prize.json”, From the existing file “ nobel_prize.json” Transfer storage data .

Example (JSON Deserialization of data sets ):

import json
with open('nobel_prize.json.html') as f:
data = json.load(f)
for nobel_prize in data['prizes']:
print(nobel_prize['year'],nobel_prize['category'])

Output :

This code snippet shows the code from JSON File to its corresponding Python Changes to objects .

I hope you are interested in JSON Parsing , All the concepts about serialization and deserialization are clear .

 

Click to follow , The first time to learn about Huawei's new cloud technology ~

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/04/20210407123015429r.html

  1. Python brush questions - letter graphics
  2. Python数据分析入门(七):Pandas层级索引
  3. Introduction to Python data analysis (7): Pandas hierarchical index
  4. Python 操作腾讯云短信(sms)详细教程
  5. Python operation Tencent cloud SMS (SMS) detailed tutorial
  6. Python数据可视化,完整版实操指南 !
  7. Python data visualization, full version of the practical guide!
  8. 上手Pandas,带你玩转数据(2)-- 使用pandas从多种文件中读取数据
  9. 上手Pandas,带你玩转数据(1)-- 实例详解pandas数据结构
  10. Using pandas to read data from various files
  11. Hands on pandas, take you to play with data (1) -- detailed explanation of pandas data structure with examples
  12. Pandas数据结构基础用法
  13. Basic usage of pandas data structure
  14. Python读取ini配置文件,保存到对象属性
  15. Python reads the INI configuration file and saves it to the object properties
  16. Foundation of Python: classes in Python
  17. python刷题-闰年判断
  18. python刷题-01字串
  19. How to judge leap year
  20. Python brush title-01 string
  21. 安装python
  22. 按尺寸切片pandas数据集DataFrame到多个文件
  23. Install Python
  24. Slice the pandas dataset dataframe to multiple files by size
  25. python 求最大值、最小值、平均值
  26. Finding maximum, minimum and average in Python
  27. 认识Python解释器和PyCharm编辑器
  28. Know Python interpreter and pycharm editor
  29. Python 小数据池和代码块缓存机制
  30. Python small data pool and code block caching mechanism
  31. python刷题-序列求和
  32. python刷题-圆的面积
  33. Sequence summation in Python
  34. The area of a circle
  35. Python functions, advanced syntax and usage
  36. Teach you to crawl novels in Python! Who can pay for novels these days!
  37. Python入门学习之:10分钟1500访问量
  38. Introduction to Python: 1500 visits in 10 minutes
  39. 数据分析之Pandas合并操作总结
  40. OpenCV-Python 雪花飘落特效
  41. Pandas merge operation summary of data analysis
  42. Opencv Python snowflake falling effect
  43. python logging模块“另一个程序正在使用此文件,进程无法访问。”问题解决办法
  44. Python logging module "this file is being used by another program and cannot be accessed by the process." Problem solving
  45. Mac 下python3 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed 解决方法
  46. Python 3 [SSL: Certificate] on MAC_ VERIFY_ Failed] certificate verify failed solution
  47. Python学习之解决python下载第三方依赖速度慢的问题
  48. Python learning to solve the problem of slow download speed of third party dependence on Python
  49. python操作Excel文件报lrd.biffh.XLRDError
  50. How to operate excel file with Python lrd.biffh.XLRDError
  51. 2021的挑战与机遇,今年Python数据分析岗位会很香!
  52. The challenge and opportunity of 2021, python data analysis post will be very popular this year!
  53. 【C++简明教程】Python和C++指定元素排序比较
  54. Comparison of Python and C + + specified element sorting
  55. Python Flask使用Nginx做代理时如何获取真实IP
  56. How to get real IP address when Python flash uses nginx as proxy
  57. Python培训出来好找工作吗?好找工作的关键是什么?
  58. Is Python training easy to find a job? What is the key to finding a good job?
  59. 从零开始学python | 什么是Python JSON?
  60. Learn Python from scratch | what is Python JSON?