zoukankan      html  css  js  c++  java
  • 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)
    
  • 相关阅读:
    Jquery选择器 选择一个不存在的元素 为什么不会返回 false
    flask接收前台的form数据
    virtualenv
    easy_install与pip 区别
    Linux安装Python2.7
    能者多劳
    西游记的管理智慧:选择团队领导人的核心奥秘
    最高管理智慧:留个缺口给别人
    团队管理的1 4 7法则
    Spring的AOP面向切面编程
  • 原文地址:https://www.cnblogs.com/xixiaohui/p/12156622.html
Copyright © 2011-2022 走看看