zoukankan      html  css  js  c++  java
  • python中json操作

    1、写操作.json文件dumps()、dump()函数

     1 d = {
     2     'zll': {
     3         'addr': '北京',
     4         'age': 28
     5     },
     6     'ljj': {
     7         'addr': '北京',
     8         'age': 38
     9     }
    10 }
    1 fw = open('user_info.json', 'w', encoding='utf-8')
    2 # ensure_ascii:默认值True,如果dict内含有non-ASCII的字符,则会类似uXXXX的显示数据,设置成False后,就能正常显示
    3 # dic_json = json.dumps(d,ensure_ascii=False,indent=4)  #字典转成json格式,字典转成字符串
    4 dic_json = json.dumps(d, ensure_ascii=True, indent=4)  # 字典转成json格式,字典转成字符串
    5 fw.write(dic_json)
    6 fw.close()
    结果
     1 {
     2     "zll": {
     3         "addr": "u5317u4eac",
     4         "age": 28
     5     },
     6     "ljj": {
     7         "addr": "u5317u4eac",
     8         "age": 38
     9     }
    10 }

     1 fw = open('user_info.json', 'w', encoding='utf-8')
     2 # ensure_ascii:默认值True,如果dict内含有non-ASCII的字符,则会类似uXXXX的显示数据,设置成False后,就能正常显示
     3 dic_json = json.dumps(d,ensure_ascii=False,indent=4)  #字典转成json,字典转成字符串
     5 fw.write(dic_json)
     6 fw.close()

    7 结果
    {  9 "zll": { 10 "addr": "北京", 11 "age": 28 12  }, 13 "ljj": { 14 "addr": "北京", 15 "age": 38 16  } 17 }

    dump() 操作json文件 写的操作

     1 fw = open('user_info.json', 'w', encoding='utf-8')
     2 json.dump(d,fw,ensure_ascii=False,indent=4)  #操作文件
     3 fw.close()
     4 
     5 结果
     6 {
     7     "zll": {
     8         "addr": "北京",
     9         "age": 28
    10     },
    11     "ljj": {
    12         "addr": "北京",
    13         "age": 38
    14     }
    15 }

    2、读操作load()、loads()

     1 # json串是一个字符串
     2 f = open('product.json',encoding='utf-8')
     3 res = f.read()
     4 product_dic = json.loads(res)  #把json串,变成python的数据类型,只能转换json串内容
     5 print(product_dic)
     6 print(product_dic['iphone'])
     7 # t = json.load(f)
     8 # print(t) #传一个文件对象,它会帮你直接读json文件,并转换成python数据
     9 # print(t['iphone'])
    10 f.close()
    11 
    12 结果
    13 {'iphone': {'color': 'red', 'num': 1, 'price': 98.5}, 'wather': {'num': 100, 'price': 1, 'color': 'white'}}
    14 {'color': 'red', 'num': 1, 'price': 98.5}
     1 # 文件读写
     2 def op_file(file, dict_temp=None):
     3     if dict_temp:
     4         with open(file, 'w', encoding='utf-8') as fw:
     5             json.dump(dict_temp, fw, ensure_ascii=False, indent=4)
     6         return 1
     7     else:
     8         with open(file, 'r', encoding='utf-8') as fr:
     9             dict_temp = json.load(fr)
    10         return dict_temp
  • 相关阅读:
    powerpc调试工具的使用
    微软的开发工具是我见过比较难用的
    Spring之jdbcTemplate:查询的三种方式(单个值、单个对象、对象集合)
    静态工厂方法和实例工厂方法
    理解.NET Framework
    .NET相关的概念简介
    二、文档工具 swagger
    Java Web学习(二)数据加密
    Java Web学习(一)Web基础
    Oracle学习(十二)标量函数
  • 原文地址:https://www.cnblogs.com/xinjing-jingxin/p/8857070.html
Copyright © 2011-2022 走看看