zoukankan      html  css  js  c++  java
  • Python_json

     1 import json
     2 '''
     3 Python内置了json包来帮助我们完成对json的操作。
     4 将Python的字典结构导出到json使用json.dumps(),将json读成Python的字典结构,使用json.loads()
     5 如果不是针对string操作而是对文件操作,分别使用json.load()函数和json.dump()函数。
     6 '''
     7 data = {
     8     'name':'ACME',
     9     'shares':100,
    10     'price':542.23
    11 }
    12 json_str = json.dumps(data)
    13 data = json.loads(json_str)
    14 
    15 #Writing Json data to file
    16 with open('data.json','w') as f:
    17     json.dump(data,f)
    18 
    19 #Reading data back
    20 with open('data.json','r') as f:
    21     data = json.load(f)
    22 
    23 
    24 '''其他数据类型与Json之间的编码和解码
    25 Json                      Python
    26 object                    dict
    27 array                     list
    28 string                    unicode
    29 number(int)               int,long
    30 number(real)              float
    31 true                      True
    32 false                     False
    33 null                      None
    34 
    35 一般来说,Python对json的解析是list或dict之间的操作,如果需要其他类型与json之间交换,就需要object_hook参数。
    36 先定义一个类,将类的字典初始化成json的key-value键值对。这样,json的参数就变成了类的属性
    37 '''
    38 x=[1,2,3]
    39 y=json.dumps(x)  #对列表进行编码
    40 print('......')
    41 y1=json.loads(y)
    42 print(json.loads(y))   #解码
    43 print(type(y1))
    44 # <class 'list'>
    45 x1={'a':1,'b':2,'c':3}
    46 y2=json.dumps(x1)   #对字典进行编码
    47 print(type(y2))
    48 # <class 'str'>
    49 y3=json.loads(y2)
    50 print(y3)
    51 # {'c': 3, 'b': 2, 'a': 1}
    52 print(type(y3))
    53 # <class 'dict'>
    54 fp=open('test.txt','a+')
    55 json.dump({'a':1,'b':2,'c':3},fp)   #对字典进行编码并写入文件
    56 fp.close()
  • 相关阅读:
    dva实用的学习笔记
    上传图片到七牛云
    Lodash学习笔记
    Ant Design Pro 脚手架+umiJS 实践总结
    SVN的安装和使用手册
    判断数据类型的5种方法
    常见react面试题汇总(适合中级前端)
    Es6 类class的关键 super、static、constructor、new.target
    ES2019 新特性简介
    通用正则实战200
  • 原文地址:https://www.cnblogs.com/cmnz/p/6978772.html
Copyright © 2011-2022 走看看