如何基于python操作json文件获取内容

yipeiwu_com7年前Python基础

这篇文章主要介绍了如何基于python操作json文件获取内容,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

写case时,将case 写到json文件比写到,写python一定要学会处理json

以下,是要处理的json

处理操作包括:打开json文件,获取json文件内容,关闭json文件,读取内容中的对应key的value

{
  "name": "BeJson",
  "url": "http://www.bejson.com",
  "page": 88,
  "isNonProfit": true,
  "address": {
    "street": "科技园路.",
    "city": "江苏苏州",
    "country": "中国"
  },
  "links": [
    {
      "name": "Google",
      "url": "http://www.google.com"
    },
    {
      "name": "Baidu",
      "url": "http://www.baidu.com"
    },
    {
      "name": "SoSo",
      "url": "http://www.SoSo.com"
    }
  ]
}

python实现:

#coding=utf-8
import json

class OperationJson:
  def __init__(self,file_name=None):  
    if file_name:
      self.file_name = file_name
    else:
      self.file_name = './dataConfig/data.json'
    self.data = self.get_data()
    
  def get_data(self):
    fp = open(self.file_name)
    data = json.load(fp)
    fp.close()
    return data
  
  def get_value(self,id):
    return self.data[id]

if __name__ == '__main__':
  opers = OperationJson()
  print opers.get_value('name')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现matplotlib显示中文的方法详解

Python实现matplotlib显示中文的方法详解

本文实例讲述了Python实现matplotlib显示中文的方法。分享给大家供大家参考,具体如下: 【注意】 可能与本文主题无关,不过我还是想指出来:使用matplotlib库时,下面两...

python3+PyQt5+Qt Designer实现堆叠窗口部件

python3+PyQt5+Qt Designer实现堆叠窗口部件

本文是对《Python Qt GUI快速编程》的第9章的堆叠窗口例子Vehicle Rental用Python3+PyQt5+Qt Designer进行改写。 第一部分无借用Qt De...

python实现读取并显示图片的两种方法

在 python 中除了用 opencv,也可以用 matplotlib 和 PIL 这两个库操作图片。本人偏爱 matpoltlib,因为它的语法更像 matlab。 一、matplo...

python内存管理分析

python内存管理分析

本文较为详细的分析了python内存管理机制。分享给大家供大家参考。具体分析如下: 内存管理,对于Python这样的动态语言,是至关重要的一部分,它在很大程度上甚至决定了Python的执...

python中的turtle库函数简单使用教程

python中的turtle库函数简单使用教程

具体内容如下所示: 参考案例: import turtle d=0 for i in range(4): turtle.fd(200) #或者写成turtle.fo...