New to python and working with jsons. I've managed to load all my jsons into a loop and output the location and the value I'm looking for using the print command. But how do I get the username data to be saved into a txt or csv?
My working code:
import json
from pathlib import Path
for f in Path(mypath).rglob('*.json'):
data = json.loads(f.read_text())
print(mypath)
print(data['customer'][0]['lname'])
f = open("testfile.txt", "a")
f.write(#i know need to pass something here but no luck)
f.close()
I just want to extract the same value from all my jsons and just output it to a file. Any help?
layout of my jsons:
{
"sheduledTime": "9:30",
"startDateForStartDate": "01/29/2020",
"endDateForStartDate": "02/03/2020",
"customer": [
{
"fname": "somedata",
"lname": "somedata",
"username": "somedata"
}
]
}
``
CodePudding user response:
This is how I would implement it. This code reads all user information and writes it into a text file.
import json
import os
mypath = "PATH_TO_FOLDER" #path must end with a "/"
for path in os.listdir(mypath):
if path.endswith(".json"):
with open(mypath path, 'r') as file:
data = json.load(file)
with open("testfile.txt", "a") as f:
for key, value in data['customer'][0].items(): # loops through all keys that the customer object has
f.write(value '\n')
for just the username use this code:
import json
import os
mypath = "PATH_TO_FOLDER"
for path in os.listdir(mypath):
if path.endswith(".json"):
with open(mypath path, 'r') as file:
data = json.load(file)
with open("testfile.txt", "a") as f:
f.write(data['customer'][0]["username"])
f.write("\n")
