zoukankan      html  css  js  c++  java
  • Python--json处理

    import json

    # json串就是字符串
    d = {
    'car': {'color': 'red', 'price': '100', 'count': 50},
    'car1': {'color': 'red', 'price': '100', 'count': 50},
    'car2': {'color': 'red', 'price': '100', 'count': 50},
    '汽车': {'color': 'red', 'price': '100', 'count': 50},
    }
    res = json.dumps(d, indent=4, ensure_ascii=False) # 把list/字典转为json,indent多少缩进,ensure_ascii 可以显示中文
    print(res)

    with open('f1', 'w', encoding='utf-8') as f:
    f.write(res)

    with open('f1', encoding='utf-8') as f:
    res = f.read()
    dict_res = json.loads(res) # 把json变为python的数据类型
    print(type(dict_res))
    print(dict_res)

    # json中必须为双引号

    # 自动的帮你写入文件,第一个参数是数据,第二个是文件对象
    with open('f1', 'w', encoding='utf-8') as f:
    json.dump(d, f, ensure_ascii=False, indent=4)

    # 自动的帮你读文件
    with open('f1', encoding='utf-8') as f:
    print(json.load(f))
  • 相关阅读:
    Mayan游戏
    选择客栈
    Redundant Paths
    中心选址
    辗转相除
    字符串
    线段覆盖
    配置魔药
    宝库通道
    教官的监视
  • 原文地址:https://www.cnblogs.com/wangsilei/p/8317888.html
Copyright © 2011-2022 走看看