美文网首页
Python3 中JSON文件的使用

Python3 中JSON文件的使用

作者: lgdhang | 来源:发表于2019-08-13 00:13 被阅读0次

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。

    1. JSON常用函数

    json.dump()      # 将Python内置类型序列化为json对象后写入文件
    json.dumps()    # 将 Python 对象编码成 JSON 字符串
    json.load()        # 读取文件中json形式的字符串元素转化为Python类型
    json.loads()     # 将已编码的 JSON 字符串解码为 Python 对象
    

    2. JSON操作

    1) json.dump()

    import json
    
    data={'a': 1, 'b': 2, 'c': 3}
    
    with open('json1.txt', 'w+') as f:
        json.dump(data, f)
    

    运行结果生成json1.txt文件。

    2) json.dumps()

    json1 = json.dumps(data)
    
    print(json1)
    
    {"a": 1, "b": 2, "c": 3}
    

    最下面一行为输出结果,注意这里单引号变为了双引号。

    3) json.load()

    with open('json1.txt', 'r') as f:
        print(json.load(f))
        
    {'a': 1, 'b': 2, 'c': 3}
    

    注意这里为单引号。

    4) json.loads()

    print(json.loads(json1))
    
    {'a': 1, 'b': 2, 'c': 3}
    

    3. 总结

    对于dumps和loads方法,都是与字符串相关的,而不带s的方法都是和文件相关的。
    注意:使用loads方法读json文件,需要先打开文件。

    json_file = 'VOT2019.json'
    
    with open(json_file, encoding='utf-8') as f:
            content = f.read()
        
    data = json.loads(content)
    

    相关文章

      网友评论

          本文标题:Python3 中JSON文件的使用

          本文链接:https://www.haomeiwen.com/subject/cwkmjctx.html