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)
    
  • 相关阅读:
    vue2 生命周期
    javascript http库axios
    vue2自定义事件之$emit
    php配置rewrite模块
    php 正则匹配中文(转)
    php常用自定义函数
    Mysql----MySQL的mysql_insert_id和LAST_INSERT_ID(转)
    Mysql----mysql启动服务时提示"服务名无效"
    div+css布局
    php常见问题以及解决方法
  • 原文地址:https://www.cnblogs.com/xixiaohui/p/12156622.html
Copyright © 2011-2022 走看看