wt11

1.  json数据格式:

data = [
           {"key1":"xxx","item":"ddd"},
           {"key2":"xxxxx","item":"sss"}   
]

2. 将data写入文件中保存

datas = json.dumps(data,ensure_ascii=False,indent=4)  #ensure_ascii:使用中文保存,缩进为4个空格
    with open(\'/report/fake/mock.json\',\'w+\') as f: 
        f.write(datas)

3.读取json文件

    with open(\'/report/fake/mock.json\',\'r\') as f:
            datas = json.load(f)
            print datas

 4.使用python的json模块序列化时间或者其他不支持的类型时会抛异常,需要对json做下扩展,让它可以支持datetime类型

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime(\'%Y-%m-%d %H:%M:%S\')
        elif isinstance(obj, date):
            return obj.strftime(\'%Y-%m-%d\')
        else:
            return json.JSONEncoder.default(self, obj)

调用json.dumps时需要指定cls参数为ComplexEncoder
json.dumps({\'now\':now}, cls=ComplexEncoder)

5.将字符串类型的列表(或字典)转成列表(或字典),需要转换成unicode,再转换成list(或dict)

            config_datas = data.get(\'Value\', \'\')
            # 此时config_datas是字符串类型的列表,需要转换成unicode,再转换成list
            config_datas = config_datas.decode(\'unicode-escape\')
            config_datas = json.loads(config_datas)
            

 

分类:

技术点:

相关文章:

  • 2021-11-21
  • 2021-07-27
  • 2021-08-05
  • 2021-12-16
  • 2019-03-01
  • 2021-11-04
  • 2021-12-16
  • 2021-12-02
猜你喜欢
  • 2019-02-07
  • 2022-01-01
  • 2021-05-17
  • 2022-01-01
  • 2021-10-28
  • 2018-08-21
  • 2021-11-15
相关资源
相似解决方案