python中json解析中文处理

读取

  • 读取字符串

    1
    2
    3
    4
    5
    import json

    str = "{a:1}"
    j_data = json.loads(str)
    print(j_data)
  • 读取文件

    区别仅仅是,load 不要 s

    1
    2
    3
    4
    5
    import json

    # windows系统 open 读取可能需要指定编码
    j_data = json.load(open("文件名", "r"))
    print(j_data)

保存

  • 方法一

    1
    2
    3
    4
    5
    6
    7
    8
    import json

    data = {"a":1}

    # windows系统 open 写入可能需要指定编码
    # indent自动格式化
    # ensure_ascii 中文显示没问题
    json.dump(data, open("test.json", 'w'), indent=4, ensure_ascii=False)
  • 方法二

    区别仅仅是,dumps

    1
    2
    3
    4
    5
    6
    7
    8
    import json

    data = {"a":1}

    s = json.dumps(data, indent=4, ensure_ascii=False)

    with open("test.json", 'w') as file:
    file.write(s)

本文作者:yuhldr
本文地址https://yuhldr.github.io/posts/a63b796.html
版权声明:转载请注明出处!