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')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM