ITPub博客

首页 > 应用开发 > > python读写json

python读写json

作者:gabbro 时间:2019-08-19 15:57:14 0 删除 编辑

大致是增,删,改,读

操作json本质上是把字符串转成dict, 然后对dict进行增删改,最后再转成字符串,具体看代码

#!/usr/bin/python3

import sys
import os
import json

# 操作json本质上是把字符串转成dict, 然后对dict进行增删改,最后再转成字符串
def TestJson(resFile):
    try:
        resFp = open(resFile, "r")
        dstJson = json.load(resFp)
        resFp.close()
    except Exception as e:
        dstJson = {}

    if 'hello' not in dstJson.keys():
        dstJson['hello'] = 'hello world!' #不存在则添加否修改
        print(dstJson['hello'])
    else:
        del dstJson['hello'] # 如果存在,则删除

    if 'list' not in dstJson.keys():
        dstJson['list'] = [1, 2] # 不存在则生成[1, 2]
    else:
        dstJson['list'].append(3) # 存在则添加一个3
    print(dstJson['list'])

    if 'dtest' not in dstJson.keys():
        dictAdd = {'dtest':'value'}
        dstJson.update(dictAdd) # dict合并dict

    strJson = json.dumps(dstJson)

    with open(resFile, 'w', encoding='utf-8') as of:
        of.write(strJson)
    of.close()

if __name__ == '__main__':
    TestJson(sys.argv[1])


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2873/viewspace-3143359/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 关于网络爬虫
请登录后发表评论 登录
全部评论

注册时间:2019-08-19

  • 博文量
    85
  • 访问量
    722