update the .json file key in python - python

Json file example = {"process":[{"id":0,"path":"xyz"}, {"id":1,"path":"abc"}]}
with open(process_details.json,"r") as jsonfile:
write_data= json.load(jsonfile)
for processdetails in write_data['process']:
Path = function_to_retreive_path(processdetails['id'])
Write_data[processdetails]['path'] = Path
with open("process_details.json","w") as outfile:
json.dump(write_data,outfile)
As I'm trying to update the path for each process I'm able to retrieve the path but I'm unable to update it in process_details.json file. Getting the following error as unhashable type:'dict'
Can anyone advise me on this issue

Try this:
import json
def function_to_retreive_path (id):
return str (id) + "_updated"
with open("process_details.json","r") as f:
write_data = json.load(f)
for processdetails in write_data['process']:
# debug
print (processdetails)
print (processdetails['id'])
print (processdetails['path'])
# change value
path = function_to_retreive_path (processdetails['id'])
processdetails['path'] = path
# debug
print (processdetails['path'])
with open("process_details.json","w") as outfile:
json.dump(write_data,outfile)
Anyway, your error is caused by a typo. You are using Write_data with a capital W, so Python thinks, I don't know this variable, so it is no dictionary and thus not hashable.

I can't really answer because there are some missing functions in your code so I can't run it, but the error you are facing generally means that you are using a dictionary as a key in an other dictionary.

Related

Exporting a dictionary with multiple values and importing them for later use without using pandas

I am making a program to export, import, and display employee information such as SSN, full name, phone number, salary, and email.
I use a dictionary with SSN as the key so I can look up employee information by searching for them with their SSN.
I tried to exporting the dictionary to a json file which seems to work.
I tried importing it and I get an error message: I tried this code after importing os:
CWD = os.getcwd()
JSON_CONFIG_FILE_PATH = '%s/%s' % (CWD, 'data.json')
CONFIG_PROPERTIES = {}
try:
with open(JSON_CONFIG_FILE_PATH) as data_file:
CONFIG_PROPERTIES = json.load(data_file)
print(CONFIG_PROPERTIES)
I got an error message
json.decoder.JSONDecodeError: Extra data: line 1 column 28 (char 27)
Here is how to use the json module to import and export.
import json # add this to your imports
data = {"test":"test"} # assume data is your dictionary, and make sure the file 'data.json' exists.
# Import
data = json.load(open('data.json')
# Export
with open('data.json', 'w') as JSON_Exporter:
json.dump(data, JSON_Exporter)

File handling with functions?

So I got this code that is supposed to sort a dictionary within a json file alphabetically by key:
import json
def values(infile,outfile):
with open(infile):
data=json.load(infile)
data=sorted(data)
with open(outfile,"w"):
json.dump(outfile,data)
values("values.json","values_out.json")
And when I run it I get this error:
AttributeError: 'str' object has no attribute 'read'
I'm pretty sure I messed something up when I made the function but I don't know what.
EDIT: This is what the json file contains:
{"two": 2,"one": 1,"three": 3}
You are using the strings infile and outfile in your json calls, you need to use the file description instance, that you get using as keyword
def values(infile,outfile):
with open(infile) as fic_in:
data = json.load(fic_in)
data = sorted(data)
with open(outfile,"w") as fic_out:
json.dump(data, fic_out)
You can group, with statements
def values(infile, outfile):
with open(infile) as fic_in, open(outfile, "w") as fic_out:
json.dump(sorted(json.load(fic_in)), fic_out)
You forgot to assign the file you opened to a variable. In your current code you open a file, but then try to load the filename rather than the actual file. This code should run because you assign the file object reference to my_file.
import json
def values(infile,outfile):
with open(infile) as my_file:
data=json.load(my_file)
data=sorted(data)
with open(outfile,"w"):
json.dump(outfile,data)
values("values.json","values_out.json")

random/empty characters while re-editing a json file

I apologize for the vague definition of my problem in the title, but I really can't figure out what sort of problem I'm dealing with. So, here it goes.
I have python file:
edit-json.py
import os, json
def add_rooms(data):
if(not os.path.exists('rooms.json')):
with open('rooms.json', 'w'): pass
with open('rooms.json', 'r+') as f:
d = f.read() # take existing data from file
f.truncate(0) # empty the json file
if(d == ''): rooms = [] # check if data is empty i.e the file was just created
else: rooms = json.loads(d)['rooms']
rooms.append({'name': data['roomname'], 'active': 1})
f.write(json.dumps({"rooms": rooms})) # write new data(rooms list) to the json file
add_rooms({'roomname': 'friends'})'
This python script basically creates a file rooms.json(if it doesn't exist), grabs the data(array) from the json file, empties the json file, then finally writes the new data into the file. All this is done in the function add_rooms(), which is then called at the end of the script, pretty simple stuff.
So, here's the problem, I run the file once, nothing weird happens, i.e the file is created and the data inside it is:
{"rooms": [{"name": "friends"}]}
But the weird stuff happens when the run the script again.
What I should see:
{"rooms": [{"name": "friends"}, {"name": "friends"}]}
What I see instead:
I apologize I had to post the image because for some reason I couldn't copy the text I got.
and I can't obviously run the script again(for the third time) because the json parser gives error due to those characters
I obtained this result in an online compiler. In my local windows system, I get extra whitespace instead of those extra symbols.
I can't figure out what causes it. Maybe I'm not doing file handling incorrectly? or is it due to the json module? or am I the only one getting this result?
When you truncate the file, the file pointer is still at the end of the file. Use f.seek(0) to move back to the start of the file:
import os, json
def add_rooms(data):
if(not os.path.exists('rooms.json')):
with open('rooms.json', 'w'): pass
with open('rooms.json', 'r+') as f:
d = f.read() # take existing data from file
f.truncate(0) # empty the json file
f.seek(0) # <<<<<<<<< add this line
if(d == ''): rooms = [] # check if data is empty i.e the file was just created
else: rooms = json.loads(d)['rooms']
rooms.append({'name': data['roomname'], 'active': 1})
f.write(json.dumps({"rooms": rooms})) # write new data(rooms list) to the json file
add_rooms({'roomname': 'friends'})

How to read a json file, find a key and bring the related data as object on Python?

I'm kinda new to Python and hence learning by doing, so here I am asking for some heads up.
I need to store values in a JSON file, and later in the next execution check first if the user already requested access into the system to provide the proper returns.
So basically my json file will be:
{instance_id : 1111 {'username':'Dummy_User','email':'dummy#user.com','domain':'local','role':'admin','instance':'production','group':'administrators','state':'failed','description':'User Dummy_User is already a member of group administrators'}
},
{instance_id : 2222 {'username':'Dummy_User1','email':'dummy#user.com','domain':'local','role':'admin','instance':'production','group':'administrators','state':'success','description':'User Dummy_User1 added to the administrators group'}
}
I need to be able to query it by instance_id and get as return all of the fields, or a particular one.
Example:
result = checkJson(1111)
print (result.state + " - " + result.description)
>> failed - User Dummy_User is already a member of group administrators
What I'm currently doing: I'm writing the file using "with open" funcion but it is not separating the "objects" by comma in the file, hence it is not being recognizable as a valid json later
def write_json(self, data, filename):
with open(filename,'r+') as f:
json_data = json.load(f)
json_data.update(data)
f.seek(0)
json.dump(json_data, f)
Any thoughts on the best way to do that?
Thank you in advance!
I figured. As per my example, I could get it done by:
Writing in the json:
userInput = {id : {"username":username,"adgroup":adgroup}}
filename = "path\to\file.json"
with open(filename,"r+") as f:
json_data = json.load(f)
json_data.update(data)
f.seek(0)
json.dump(json_data, f)
This will create an object of userInput and add to the json within the agregate structure.
Later, to read this json I used:
jsonFile = "path\to\file.json"
with open(jsonFile) as access:
data = json.load(access)
instance = data[id]['username']
name = data[id]['adgroup']
where ID is the ID stored in the JSON to identify that object you saved before.

Python json.dump results in 'str' has no attribute 'dump'

I am trying to read a JSON file which contains just an object with one property which is the index. That is successful but when i try to rewrite to the same JSON file i get an error.
The code is bellow :
import sys
import json
import os
import os.path
import json
try:
json_path = path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'indexes', 'table_index.json')
with open(json_path) as json_file:
data = json.load(json_file)
index1 = 4
data["index"] = index1
print(type(data)) #Prints 'dict'
with open((json_path), 'wb') as f:
json.dump(data, f)
except Exception as e:
print(e)
The error i get is
'str' object has no attribute 'dump'
What i am basically trying to achieve is read the JSON, change the index property to a different value and at the end rewrite to the same JSON file.
Printing data["index"] before writing gives the correct value of 4.
As discussed in the comments, the most likely reason is that you define somewhere in your code a variable called json which shadows the module name. For example,
import json
json_string = '{"something": 4}'
print(json.dumps(json_string)) # prints "{\"something\": 4}"
If you, however, make an assignment like this:
json = '{"something_else": 4}'
and then call the same command as above
print(json.dumps(json_string))
it will raise
AttributeError: 'str' object has no attribute 'dumps'
So, all you have to do is to check in your code whether you made an assignment like this, change it and the issue should be resolved.

Categories