文章目录

  • 一、背景
  • 1.序列化
  • 1.1 json.dump()
  • 1.2 to_json()
  • 1.3json.dumps()
  • 2.反序列化
  • 2.1 json.load()
  • 2.2 read_json()
  • 2.3 json.loads()
  • 一、背景

    json格式是一种轻量级的数据交换格式,结构上为键值对的形式,常见于爬虫和数据分析应用领域。Python中有json和pickle两个库可以处理json格式。
    json和pickle库提供了四种处理方法:dumps,dump,loads,load

    json数据处理类型

  • 序列化:将python的数据转换为json格式的字符串
  • 反序列化:将json格式的字符串转换为python类型
  • 1.序列化

    1.1 json.dump()

    常用于对文件的读写操作,该方法将字典类型数据写入json格式文件。

    import json
    student = {'name':'Job', 'age':'26'}
    with open('student_list.json', 'w+') as file:
    	json.dump(student, file)	
    

    1.2 to_json()

    效果同上。

    import pandas as pd
    student_list= [['Job', '26'],['MIke', '23']]
    
    # 整合成dataframe格式
    df = pd.Dataframe(student_list, columns=['name', 'age'])
    with open('student_list.json', 'w+') as file:
    	df.to_json(file, orient='index')
    

    1.3json.dumps()

    与上述json.dump()的区别是:json.dump()聚焦于数据本身类型的转换,对数据的操作。

    import json
    student = {'name':'Job', 'age':'26'}
    student_json = json.dumps(student)
    print(type(student_json))
    

    2.反序列化

    2.1 json.load()

    主要处理json格式文件,将json格式数据转换为python可读的字典类型,可对其中的键值对进行数据和格式的修改。

    import json
    
    with open('student_list.json', 'r') as json_file:
    	students = json.load(json_file)
    
    print(students)
    print(type(students)) # dict类型
    print(studnets['name'])
    

    2.2 read_json()

    效果同上。

    import pandas as pd
    
    with open('student_list.json', 'r') as json_file:
    	df_students = pd.read_json(json_file, orient='index')
    print(df_students.head())
    

    2.3 json.loads()

    与json.load()的主要区别是:json.laods()主要是对json编码的字符串进行数据类型的转换。

    import json
    
    students = json.loads(studnet_json)
    print(type(students)) # 将json编码的字符串转换为python的字典类型
    print(students['age']) 
    

    来源:是乔乔啊

    物联沃分享整理
    物联沃-IOTWORD物联网 » python处理json格式数据

    发表评论