JSON格式 - 帮助! [英] JSON formatting -- HELP!

查看:68
本文介绍了JSON格式 - 帮助!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有多个文件,我需要将它们格式化为一个JSON文件:



这是我拥有的文件示例:

Hi,
I have multiple files which I need to format them to be one JSON file:

Here is an example of a file which I have:

{"t": "test", "title": "test", "content": "test"}
{"t": "test2", "title": "test", "content": "test2"}





我需要的是:



What I need is to be like:

[
{"t": "test", "title": "test", "content": "test"},
{"t": "test2", "title": "test2", "content": "test2"}
]





最终会看起来像这样(注意下面的JSON类似于Above,second,one ):



It will look like this in the end (Note that the below JSON similar to the Above, second, one):

[{
		"t": "test",
		"title": "test",
		"content": "test"
	},
	{
		"t": "test2",
		"title": "testw",
		"content": "test2"
	}
]





我的尝试:



我有以下python代码:





What I have tried:

I have the below python code:

import io
import os
import json

def wrap_files_in_dir(dirname):


    data = {}

    list_of_reviews = []


    for filename in os.listdir(dirname):
        file_path = os.path.join(dirname, filename)
        if os.path.isfile(file_path):
            with io.open(file_path, 'r', encoding='utf-8', errors='ignore') as rfile:
                contents = rfile.read()
                list_of_reviews.append(contents)




    with io.open('AppStoreReviews.json', 'w', encoding='utf-8' , errors='ignore') as wfile:
        data["reviews"] = list_of_reviews
        wfile.write(unicode(json.dumps(data, ensure_ascii=False)))


if __name__ == '__main__':
    wrap_files_in_dir('/Users/Jack/PycharmProjects/MyProject')

print("Your Reviews marged and converted to JSON")







我知道我在这里遗漏了一些代码,这些代码输入到我目录中的每个文件中......或者它可能是别的东西?

有人可以帮我吗?



问题是代码确实创建了一个JSON文件,但是,JSON没有任何数组,并且在我的对象之间没有任何,。




I know that I'm missing some code here which enter to each file in my directory.. or could it be something else?
Can someone help me with this?

the problem is that the code does create me a JSON file, BUT, the JSON is without any arrays and doesn't have any "," between my objects.

推荐答案

以下代码生成(我希望)您要查找的内容:

The following code produces (I hope) what you are looking for:
import io
import os
import json

def wrap_files_in_dir(dirname):
    data = {}
    list_of_reviews = []

    for filename in os.listdir(dirname):
        file_path = os.path.join(dirname, filename)
        if os.path.isfile(file_path):
            with io.open(file_path, 'r', encoding='utf-8', errors='ignore') as rfile:
                review = json.load(rfile)
                list_of_reviews.append(review)

    with io.open('AppStoreReviews.json', 'w', encoding='utf-8' , errors='ignore') as wfile:
        json.dump(list_of_reviews, wfile, indent=2)

if __name__ == '__main__':
    wrap_files_in_dir('C:\\Users\\rjmac\\Documents\\_Python\\JFiles')

print("Your Reviews marged and converted to JSON")


对此最简单的解决方法是在每行上预先添加逗号,但是首先。

执行此操作的方法是设置变量以了解当前行是否为第一行,然后实现 if ... then



不幸的是,我知道Python就像我知道Klingon一样...所以你很可能需要按摩我所做的代码更改的变化
The easiest fix for this is to pre-pend a comma on every line but the first.
A method to do this would be to set a variable to know if the current line is the first, and then implement an if...then block

Unfortunately, I know Python just as much as I know Klingon... so you will probable need to massage the changes to the code changes I made
# create boolean variable for "IsFirst"
IsFirst = true

for filename in os.listdir(dirname):
   file_path = os.path.join(dirname, filename)
      if os.path.isfile(file_path):
         with io.open(file_path, 'r', encoding='utf-8', errors='ignore') as rfile:

            # If IsFirst, add contents as is, and set IsFirst to false
            if (IsFirst == true) 
               contents = rfile.read()
               IsFirst = false
            # if NOT IsFirst, prepend a comma to the contents

            else 
               contents = "," + rfile.read()

            list_of_reviews.append(contents)


找到解决方案:



Found the Solution:

list_of_reviews = []

   for filename in os.listdir(dirname):
       if not filename.startswith('.'):
           file_path = os.path.join(dirname, filename)
           if os.path.isfile(file_path):
        with io.open(file_path, 'r', encoding='utf-8', errors='ignore') as rfile:
                   lines = rfile.readlines()
                   for line in lines:
                       line = line.rstrip()
                       review = json.loads(line)
                       list_of_reviews.append(review)





感谢所有帮助过的人!



THANKS To every one which helped!


这篇关于JSON格式 - 帮助!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆