Python 加載包含多個JSON對象的JSON文件


def writeJsonFile(data,outfilename):
    with open(outfilename+'.json', 'wt',encoding='utf-8') as f:
        for m in data:
            json.dump(m,f,ensure_ascii=False,indent=4)
        f.close()

 

把兩個List寫入test.json

 

def test():
    result =[1,2,3]

    temp ={
        'test':result
    }
    content =[]
    content.append(temp)
    content.append(temp)
    writeJsonFile(content,'test')

 

於是便有了一個test.json

{
    "test": [
        1,
        2,
        3
    ]
}{
    "test": [
        1,
        2,
        3
    ]
}

 

那么問題來了。

讀取文件

def readJsonFile(file_name):
	data =[]
	with open(file_name,'r',encoding='utf-8') as f:
		
		data = json.load(f)
		f.close()
	return data

 

顯示錯誤:

json.decoder.JSONDecodeError: Extra data: line 7 column 2 (char 55)

如果test.json文件是這樣的

{
    "test": [
        1,
        2,
        3
    ]
}

那么用如上的讀取方法,是沒有問題的。

這該怎么辦呢?

思路如下:

def readJsonFileToStr(file_name):

	with open(file_name,'r',encoding='utf-8') as f:

		text = f.read()
		f.close()
	return text

 

先把文件讀取成字符串,

然后把“}{”替換成“}aaaaa{” 再用'aaaaa'進行字符串分割!

使用json.loads(str)對每個分割后的字符串進行轉換。

 

def read():
	text = readJsonFileToStr('test.json')

	objs = text .replace('}{','}aaaaa{')

	# print(objs)
	objs = objs.split('aaaaa')

	print(len(objs))
        
	for item in objs:
		data = json.loads(item)
                print(data)

 


免責聲明!

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



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