1. 程式人生 > >一種另類的讀取 json 資料方式

一種另類的讀取 json 資料方式

ValueError: Expecting property name enclosed in double quotes: line 1 column 2(char 1)

在做 scrapy 爬蟲時,獲取的資料存入 json 時有些資料格式不對,導致各種問題。不僅是字元編碼,還有格式。搜了半天的解決辦法都不行。所以就自己利用基本知識,編寫了一個比較全能的讀取方式,只要是文字檔案就可以讀取。 因為寫入的 json 資料是一行行的,所以我就先一行行讀取所有的檔案,然後利用 eval 函式將文字轉化為 json 資料就實現讀取了。然後再用列表收集,就可以自己處理成其他格式了。

json_dict = []
with
open("items2.json", encoding='utf-8') as f: for line in f.readlines(): try: json_dict.append(eval(line)) except Exception as e: pass file = open('data.json', 'w', encoding='utf-8') line = json.dumps(json_dict) file.write(line) file.close()