Python读取JSON文件示例

小林子
小林子
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍如何使用Python标准库json模块读取JSON文件。通过open打开文件,利用json.loads解析字符串为字典对象,并演示如何访问嵌套字段。文末提供多个在线JSON格式化工具链接,辅助开发者进行代码校验与美化。

本文通过一个具体实例,展示如何使用Python读取JSON文件,供读者参考学习。

示例数据文件read_json.json的内容如下:

{
  "rule":{
    "namespace":"strategy",
    "name":"test_exp_1496234234223400",
    "version":0,
    "last_modify_time":1434234236819000,
    "log_rate":1023300,
    "schema_version":"hello_world!"
  }
}

对应的Python脚本read_json.py实现代码如下:

# -*- coding:utf-8 -*-
import json
with open("read_json.json", 'r') as f:
  temp = json.loads(f.read())
  print(temp)
  print(temp['rule'])
  print(temp['rule']['namespace'])

执行上述脚本后,控制台输出结果如下:

{u'rule': {u'name': u'test_exp_1496234234223400', u'log_rate': 1023300, u'namespace': u'strategy', u'schema_version': u'hello_world!', u'last_modify_time': 1434234236819000L, u'version': 0}}
{u'name': u'test_exp_1496234234223400', u'log_rate': 1023300, u'namespace': u'strategy', u'schema_version': u'hello_world!', u'last_modify_time': 1434234236819000L, u'version': 0}
strategy

此外,关于JSON文件的处理,以下推荐几款实用的在线工具供参考:

在线JSON代码检验、校验、美化及格式化工具: http://tools.jb51.net/code/json

JSON在线格式化工具: http://tools.jb51.net/code/jsonformat

在线XML与JSON互转工具: http://tools.jb51.net/code/xmljson

JSON代码在线格式化、美化、压缩、编辑及转换工具: http://tools.jb51.net/code/jsoncodeformat

在线JSON压缩与转义工具: http://tools.jb51.net/code/json_yasuo_trans

如需了解更多Python相关知识,可查阅本站相关专题,包括《Python操作json技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》以及《Python文件与目录操作技巧汇总》。

希望本文提供的示例对大家进行Python程序设计有所帮助。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表