I'm trying to append a list with new names in a json file.
JSON structure:
{
"users": [
"User1",
"User2",
"User3"
]
}
I have tried this:
with open('data/users.json', 'r') as json_file:
json_data = json.load(json_file)
user_list = json_data["users"]
with open('data/users.json', 'w') as json_file:
user_list.append(name)
json.dump(user_list, json_file)
But it turns out like this:
["User1", "User2", "User3", "User4"]
Why and how do I fix it?
You need to write the whole data dictionary, not just the list
with open('data/users.json', 'r') as json_file:
json_data = json.load(json_file)
json_data["users"].append(name)
with open('data/users.json', 'w') as json_file:
json.dump(json_data, json_file)
Related
I'm trying to convert a CSV file into a jSON file in order to then inject it into a Firebase database.
csvfile = open('final_df_2.csv', 'r')
jsonfile = open('final_df_5.json', 'w')
reader = csv.DictReader(csvfile)
for row in reader:
json.dump({row['ballID']: [{"colour": row['colour'], "radius":row['radius']}]}, jsonfile)
jsonfile.write('\n')
Unfortunately, I keep getting an "End of File expected" error
Here's my JSON's output
{
"001": [
{
"colour": "green",
"radius": "199405.0"
}
]
}
{
"002": [
{
"colour": "blue",
"radius": "199612.0"
}
]
}
In addition, Firebase sends back an error when I try to import the JSON file saying "Invalid JSON files"
You could collect all the data into a python list and dump that list to the json file:
csvfile = open('final_df_2.csv', 'r')
reader = csv.DictReader(csvfile)
jsoncontent = []
for row in reader:
jsoncontent.append({row['ballID']: [{"colour": row['colour'], "radius":row['radius']}]})
with open('final_df_5.json', 'w') as jsonfile:
json.dump(jsoncontent, jsonfile)
However, I'm not sure what your firebase database is expecting.
I am trying to covert my CSV email list to a JSON format to mass email via API. This is my code thus far but am having trouble with the output. Nothing is outputting on my VS code editor.
import csv
import json
def make_json(csvFilePath, jsonFilePath):
data = {}
with open(csvFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
for rows in csvReader:
key = rows['No']
data[key] = rows
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonf.write(json.dumps(data, indent=4))
csvFilePath = r'/data/csv-leads.csv'
jsonFilePath = r'Names.json'
make_json(csvFilePath, jsonFilePath)
Here is my desired JSON format
{
"EmailAddress": "hello#youngstowncoffeeseattle.com",
"Name": "Youngstown Coffee",
"ConsentToTrack": "Yes"
},
Heres my CSV list
No,EmailAddress,ConsentToTrack
Zylberschtein's Delicatessen & Bakery,catering#zylberschtein.com,Yes
Youngstown Coffee,hello#youngstowncoffeeseattle.com,Yes
It looks like you could use a csv.DictReader to make this easier.
If I have data.csv that looks like this:
Name,EmailAddress,ConsentToTrack
Zylberschtein's Delicatessen,catering#zylberschtein.com,yes
Youngstown Coffee,hello#youngstowncoffeeseattle.com,yes
I can convert it into JSON like this:
>>> import csv
>>> import json
>>> fd = open('data.csv')
>>> reader = csv.DictReader(fd)
>>> print(json.dumps(list(reader), indent=2))
[
{
"Name": "Zylberschtein's Delicatessen",
"EmailAddress": "catering#zylberschtein.com",
"ConsentToTrack": "yes"
},
{
"Name": "Youngstown Coffee",
"EmailAddress": "hello#youngstowncoffeeseattle.com",
"ConsentToTrack": "yes"
}
]
Here I've assumed the headers in the CSV can be used verbatim. I'll update this with an exmaple if you need to modify key names (e.g. convert "No" to "Name"),.
If you need to rename a column, it might look more like this:
import csv
import json
with open('data.csv') as fd:
reader = csv.DictReader(fd)
data = []
for row in reader:
row['Name'] = row.pop('No')
data.append(row)
print(json.dumps(data, indent=2))
Given this input:
No,EmailAddress,ConsentToTrack
Zylberschtein's Delicatessen,catering#zylberschtein.com,yes
Youngstown Coffee,hello#youngstowncoffeeseattle.com,yes
This will output:
[
{
"EmailAddress": "catering#zylberschtein.com",
"ConsentToTrack": "yes",
"Name": "Zylberschtein's Delicatessen"
},
{
"EmailAddress": "hello#youngstowncoffeeseattle.com",
"ConsentToTrack": "yes",
"Name": "Youngstown Coffee"
}
]
and to print on my editor is it simply print(json.dumps(list(reader), indent=2))?
I'm not really familiar with your editor; print is how you generate console output in Python.
I am trying to replace data1 with data5 in json body of Full Address, but my code is giving error with these (list indices must be integers or slices, not str).
Please see my code as well as json body below.
json
[
{
"fields": {
"Full Address": "data1",
"pl/p/0": "212152",
"ot": "fgde"
}
},
{
"fields": {
"Full Address": "data2",
"pl/p/0": "52562",
"ot": "frtfr"
}
}
]
code
import json
with open('jsonbody.json') as f:
data = json.load(f)
for item in data['fields']:
item['Full Address'] = item['Full Address'].replace('data1', 'data5')
with open('new_data.json', 'w') as f:
json.dump(data, f)
the data is list, and its element is a dict, which contains fields key
import json
with open('jsonbody.json') as f:
data = json.load(f)
for item in data:
item['fields']['Full Address'] = item['fields']['Full Address'].replace('data1', 'data5')
with open('new_data.json', 'w') as f:
json.dump(data, f)
Here I am answering my own question with adding german umlaut detail.
import json
jsonbody = 'jsonbody.encode()'
with open('jsonbody.json', 'r') as file:
json_data = json.load(file)
for item in json_data:
if item['fields']['Full Address'] in ["data1"]:
item['fields']['Full Address'] = "data5_Ä"
with open('new_data.json', 'w') as file:
json.dump(json_data, file, indent=2)
# if my detail contain german words then I will use this
json.dump(json_data, file, indent=2, ensure_ascii=False)
Code Including JSON File Code:
Python( Suppose To Append A New User and Balance):
import json
with open('users_balance.json', 'r') as file:
data = json.load(file)['user_list']
data['user_list']
data.append({"user": "sdfsd", "balance": 40323420})
with open('users_balance.json', 'w') as file:
json.dump(data, file, indent=2)
Json(Object The Code Is Appending To):
{
"user_list": [
{
"user": "<#!672986823185661955>",
"balance": 400
},
{
"user": "<#!737747404048171043>",
"balance": 500
}
],
}
Error(Traceback Error Given After Executing Code):
data = json.load(file)['user_list']
KeyError: 'user_list'
The solution is this:
import json
with open('users_balance.json', 'r') as file:
data = json.load(file)
data['user_list'].append({"user": "sdfsd", "balance": 40323420})
with open('users_balance.json', 'w') as file:
json.dump(data, file, indent=2)
I am attempting to read the following JSON file and update it, specifically:
I can get the latest data analysis (var: lastAnalysisCompleted) was completed using get_json()
I get the following error code "list indices must be integers or slices, not str" when attempting to set baselineDictionaryFilename variable
I want to create a new grouping under the 'analysis' using the write_json() module. But running into errors.
How can I proceed?
New grouping:
"01-02-2020":{
"dictionaryFileName": "Dictionary_01-02-2020.json",
"analysisFileName": "Analysis_Output_01-02-2020.xlsx",
"netNewLabelledEntries": "10",
"range90": "1",
"range80": "3",
"range75":"1",
"rangeLessThan75":"5"
}
def get_json():
with open(jFile, 'r') as myfile:
data=myfile.read()
# parse file
obj = json.loads(data)
#secret = parsed_input['secret']
lastAnalysisCompleted = obj['lastAnalysisCompleted']
baselineDictionaryFileName = obj['analysis'][lastAnalysisCompleted]['dictionaryFileName']
Here is the module I wrote to update JSON but it doesn't work
def write_json(filename=jFile):
with open(filename, 'w') as f:
json.dump(data, f, indent=3)
with open(jFile) as json_file:
data = json.load(json_file)
temp = data['analysis']
y = {
"01-02-2020":{
"dictionaryFileName": "Dictionary_01-02-2020.json",
"analysisFileName": "Analysis_Output_01-02-2020.xlsx",
"netNewLabelledEntries": "10",
"range90": "1",
"range80": "3",
"range75":"1",
"rangeLessThan75":"5"
}
}
temp.append(y)
write_json(data)
Here is my JSON file.
{
"lastAnalysisCompleted": "01-01-2020",
"analysis":[
{
"12-31-2019":{
"dictionaryFileName": "Dictionary_12-31-2019.json",
"analysisFileName": "Analysis_Output_12-31-2019.xlsx",
"netNewLabelledEntries": "10",
"range90": "1",
"range80": "3",
"range75":"1",
"rangeLessThan75":"5"
},
"01-01-2020":{
"dictionaryFileName": "Dictionary_01-01-2020.json",
"analysisFileName": "Analysis_Output_01-01-2020.xlsx",
"netNewLabelledEntries": "10",
"range90": "1",
"range80": "3",
"range75":"1",
"rangeLessThan75":"5"
}
}
]
}
The problem in your code for getting the file name it is array of dicts you need to use index to access specific dictionary.
def get_json():
with open('test.json', 'r') as myfile:
data=myfile.read()
# parse file
obj = json.loads(data)
#secret = parsed_input['secret']
lastAnalysisCompleted = obj['lastAnalysisCompleted']
baselineDictionaryFileName = ''.join([d[lastAnalysisCompleted]['dictionaryFileName'] for d in obj['analysis'] if lastAnalysisCompleted in d])
And for writing to json file you are passing data to write_json() function and in function you are not defined argument for data
def write_json(data, filename=jFile):
with open(filename, 'w') as f:
json.dump(data, f, indent=3)