Take you in one minute to understand how python reads and writes json data

This article mainly introduces how to read and write json data in python in detail, which has certain reference value, and interested friends can refer to it.

The examples in this article share the specific code of python to read and write json data for your reference. The specific content is as follows

Case:

  In web applications, json data is often used to transmit data. In essence, dictionary type data is converted into string, and the string is used for web page transmission, and then the received string is converted into dictionary-like data

  Requirement: Realize the conversion of dictionary into character string, character string into dictionary data type, and write to file

How to do?

1. Clarify the difference between dumps and dump. The interface of dump is a file, which is directly written to the file. Dumps converts the corresponding data type into a string. The opposite of loads and dumps. Load reads the file directly from the file and converts the data to the corresponding The data type of
2, the first data conversion, the string as an intermediate bridge

#!/usr/bin/python3
  
import json
  
  
def w_json(data):
  # 往文件中写入json文件
  with open('json_test.json', 'w') as wf:
    json.dump(data, wf)
  print('ok')
   
      
def r_json():
  # 读取json文件
  with open('json_test.json', 'r') as rf:
    data = json.load(rf)
  return data
  
  
def chage_data(data):
  # 进行json数据转换
  try:
    # separators 会把对应符号前后的空格去掉,网络传输中,空格没有意义
    # 还可以通过sort_keys进行按字典可以排序,字典才有效,网络传输一般都用json数据格式
    return json.dumps(data, separators=[',', ':'], sort_keys=True)
  except Exception as e:
    print(e)
    return None
    
if __name__ == '__main__':
  d = {'xiao_ming': 18, 'xiao_er': 50, 'xiao_san': 17, 'xu_xue': None, 'b_l':True}
  # d = [8, 2, 2, 7, 0, None, True]
  data = chage_data(d)
    
  if data:
    w_json(data)
    r_data = r_json()
    print('读取的数据:', r_data)

The above is the whole content of this article, I hope it will be helpful to everyone's study.

end:

I am a python development engineer, and I have compiled a set of the latest python system learning tutorials, including basic python scripts to web development, crawlers, data analysis, data visualization, machine learning, and interview books. Those who want these materials can pay attention to the editor, add Q skirt 851211580 to pick up Python learning materials and learning videos, and online guidance from the Great God!

Guess you like

Origin blog.csdn.net/pyjishu/article/details/105433592