Click here to Skip to main content
15,905,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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"}
]


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"
	}
]


What I have tried:

I have the below python code:

Python
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")



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.
Posted
Updated 11-Nov-18 4:08am
v3
Comments
CHill60 9-Nov-18 9:58am    
What is the problem?
Jack Raif 9-Nov-18 9:59am    
I don't know what am I missing in my code.
Jack Raif 9-Nov-18 10:03am    
Let me be more specific, the problem is that the code do create me a JSON file, BUT, the JSON is without any arrays and doesn't have any "," between my objects.
Patrice T 10-Nov-18 13:25pm    
Show actual result
Richard MacCutchan 11-Nov-18 10:05am    
See my updated solution.

The following code produces (I hope) what you are looking for:
Python
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")
 
Share this answer
 
v4
Comments
Jack Raif 9-Nov-18 10:20am    
Great! but Im Still missing an "," between my objects..
Richard MacCutchan 9-Nov-18 10:22am    
OK, I give up. Where is it?
Jack Raif 9-Nov-18 14:02pm    
I think I know what im missing, but i need help implementing it:

list_of_reviews = [] DONE

for file in directory: - DONE

for line in file: - MISSING

review = line.parsfromjson () - MISSING
list_of_reviews.append(review) - MISSING
Richard MacCutchan 10-Nov-18 3:37am    
Reading a file line by line is easy, see section 7.2.1 at 7. Input and Output — Python 3.7.1 documentation[^].

The last two lines that you say are missing should be easy to add in the reading loop. Although I am not sure what you are trying to parse from JSON, it all depends on the data you are processing.
Richard MacCutchan 10-Nov-18 10:40am    
See my updated solution.
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
Python
# 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)
 
Share this answer
 
Comments
Richard MacCutchan 9-Nov-18 10:26am    
The JSON system will put the commas in the correct places.
MadMyche 9-Nov-18 10:30am    
Well for whatever reason, this is not happening according to the OP
Richard MacCutchan 9-Nov-18 10:46am    
Works fine in my test. And as so often, we do not get the full details.
Richard MacCutchan 9-Nov-18 10:47am    
And if you look at the results shown in the original questions, all the commas are there in the correct places.
MadMyche 9-Nov-18 11:22am    
You mean this one?

Here is an example of a file which I have:
{"t": "test", "title": "test", "content": "test"}
{"t": "test2", "title": "test", "content": "test2"}
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!
 
Share this answer
 
v2
Comments
Richard MacCutchan 11-Nov-18 10:49am    
Why do the lines, just to convert a string to json, when you can load into json directly? See my updated solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900