python指令碼分析json檔案
阿新 • • 發佈:2018-11-21
少年,想偷懶?那就複製吧:https://github.com/singgel/pythonDemo
1. 概述
JSON (JavaScript Object Notation)是一種使用廣泛的輕量資料格式. Python標準庫中的json模組提供了JSON資料的處理功能.
Python中一種非常常用的基本資料結構就是字典(Dictionary). 它的典型結構如下:
1 2 3 4 5 6 |
|
而JSON的結構如下:
1 2 3 4 5 6 |
|
可以看到, Dictionary和JSON非常接近, 而Python中的json庫提供的主要功能, 也是兩者之間的轉換.
2. 讀取JSON
json.loads方法可以將包含了一個JSON資料的str, bytes或者bytearray物件, 轉化為一個Python Dictionary.
import json def main(): # file 檔案型別的物件 with open(r'/Users/yiche/Downloads/zhangtianjia.txt', encoding="utf-8") as file: print(type(file)) print(file) # 以列表的形式輸出文字 lines = list(file) num = 0 count = 0 # 輸出文字的每一行 for eachLine in lines: num += 1 # 將 JSON 物件轉換為 Python 字典 data = json.loads(eachLine) # 這樣做的效率低 for variable in data['variables']: if variable['workflow_variable'] == 'TABLE_NAME': count += 1 print(data['name'], "\t", variable['dataset_variable']) print("num:", num) print("count:", count) if __name__ == '__main__': main()