I am trying to append value inside the list,but whenever I re run the server it overwrites the value. How can I effectively write in the json file.
{
"heart_rate": [
72.18
],
"Experiment_time": [
01/22/2023 11:59:59
]
}
I want to add values in json file, When ever I get new value it should get append inside the heartrate and Experiment_time list inside the corresponding keys, similar to below mentioned format.
{
"heart_rate": [
72.18,73.44
],
"Experiment_time": [
01/22/2023 11:59:59,01/22/2023 11:60:00
]
}
What I am tring is to first read the json file if it exists, If it doesn't create one.
try:
with open('Accounts.json','r') as fp:
data = json.load(fp)
f = data
print(f)
heartrate,dt_string = perform_all()
lst1 = []
if f != '':
print("something")
else:
lst1.append(heartrate)
except :
print("File Not found. Creating One")
data = {}
data['heart_rate'] = [None]
data['Experiment_time'] = [None]
with open('Accounts.json','w') as fp:
json.dump(data,fp,indent = 4)
heartrate,dt_string = perform_all()
is a function that returns 1 value of heartrate and 1 value of datetime when called
Close, just append to the right dictionary key. Note that JSON should be encoded in UTF-8 and not all OSes default to that encoding. It will matter if you write non-ASCII characters. Also bare except is a bad practice. Put the exception you expect.
import json
import datetime as dt
def perform_all():
return 85, dt.datetime.now().strftime('%m/%d/%y %H:%M:%S')
try:
with open('Accounts.json', encoding='utf8') as fp:
data = json.load(fp)
heartrate, dt_string = perform_all()
data['heart_rate'].append(heartrate)
data['Experiment_time'].append(dt_string)
except FileNotFoundError:
print('File not found. Creating initial data...')
data = {'heart_rate': [], 'Experiment_time': []}
with open('Accounts.json', 'w', encoding='utf8') as fp:
json.dump(data, fp, indent=2)
Output:
C:\>test
File not found. Creating one...
C:\>test
C:\>test
C:\>type Accounts.json
{
"heart_rate": [
85,
85
],
"Experiment_time": [
"01/26/23 21:34:22",
"01/26/23 21:34:23"
]
}
I need to edit a object within a dict that is located inside a json file. but whenever I attempt to do it, it would delete the entire json file and only add the thing I've edited.
Here's my function.
async def Con_Manage(keys):
with open('keys.json') as config_file:
config = json.load(config_file)[keys]
try:
Current_Con = config["curCons"] + 1
with open('keys.json', 'w') as config_file:
json.dump(Current_Con, config_file)
return True
except:
return False
heres my json file before i run it
{
"key1": {
"time": 1500,
"maxCons": 15,
"curCons": 2,
"coolDown": 2
}
}
and here's what it looks like after its ran
3
is there any way that i can run this and not delete all my progress?
config["curCons"] gets you just the value which you then increment it and assign to Current_Con. Instead you need to increment and set the value to +1. From there you would want to save the entire json object that you just read in and not just the value that was updated.
async def Con_Manage(keys):
with open('keys.json') as config_file:
config = json.load(config_file)
config[keys]["curCons"] += 1 # mutates the value in place
with open('keys.json', 'w') as keys:
json.dump(config, keys) # saves the entire dict not just the value
You need to be writing the entire config file
you can do something like this...
with open('keys.json') as config_file:
config = json.load(config_file)
for key in keys:
try:
config[key]["curCons"] += 1
except KeyError:
pass
with open('keys.json', 'w') as config_file:
json.dump(config, config_file)
As part of my homework I have to make a JSON file with class objects in it. I could do it, but the result is not that i expected.
import json
stList = []
class Student(object):
neptun_code = ""
result = 0
mark = 0
def make_student(neptun_code, result, mark):
student = Student()
student.neptun_code = neptun_code
student.result = result
student.mark = mark
stList.append(student)
def create_json():
json_string = json.dumps([ob.__dict__ for ob in stList])
with open("./data/student.txt", "w") as file:
json.dump(json_string, file)
Sample inputs for make_student : test_code, test_result, test_mark
Here is the output in student.txt:
"[{\"neptun_code\": \"test_code\", \"result\": \"test_result\", \"mark\": \"test_mark\"}]"
there are plenty of unwanted characters in it. I would like to have something like this:
[{"neptun_code": "test_code", "result": "test_result", "mark": "test_mark"}]
Can anyone explain how to do this?
You should use either dumps, or dump. Not both.
dump (my preference):
def create_json():
with open("./data/student.txt", "w") as file:
json.dump([ob.__dict__ for ob in stList], file)
OR dumps:
def create_json():
json_string = json.dumps([ob.__dict__ for ob in stList])
with open("./data/student.txt", "w") as file:
file.write(json_string)
As a side note, in the future you'll want to watch out for scoping as you're using the global object stList.
You are encoding your dictionary to JSON string twice. First you do this here:
json_string = json.dumps([ob.__dict__ for ob in stList])
and then once again, here:
json.dump(json_string, file)
Alter this line with file.write(json_string)
So I'm trying to setup json so i can store data in-between user sessions I like a name but i don't know how to add or change a specific value in an external json file like for example {"name": ""} how do i fill that "" for the json file using python?
I have already tried to use dumps and all the tutorials use dumps
the json in another file
{
"human_name": "",
"oracle_name": "",
"human_age": "",
"human_gender": "",
"oracle_gender": ""
}
the python
import json
with open('data.json', '+') as filedata:
data = filedata.read()
used_data = json.loads(data)
if str(used_data(['human_name'])) == "":
print("what is your name")
name = input()
json.dumps(name)
if str(used_data(['oracle_name'])) == "":
print("what is my name")
oracle_name = input()
json.dumps(oracle_name)
print(str(['human_name']))
The expected result is when I print the data it displays input, but when i run it it goes
File "rember.py", line 3, in
with open('data.json', '+') as filedata: ValueError: Must have exactly one of create/read/write/append mode and at most one plus
Try this code.
json.loads loads the entire json string as a python dict object. The values in a dict are changed/added using dict[key] = value. You can't call a dict object to change its value.
The json.dumps method serializes an object to a JSON formatted str. Which you can then write into the same file or a different file based on your requirement.
import json
with open('data.json', 'r') as filedata:
data = filedata.read()
used_data = json.loads(data)
if used_data['human_name'] == "":
print("what is your name")
name = input()
used_data['human_name'] = name
if used_data['oracle_name'] == "":
print("what is my name")
oracle_name = input()
used_data['oracle_name'] = oracle_name
print(used_data)
with open('data.json', 'w') as filewrite:
filewrite.write(json.dumps(used_data, indent=4))
Basically what you need to do is load json file as dictionary, add value, and save it.
import json
with open('./data.json', 'r') as f:
d = json.load(f)
d['human_name'] = 'steve'
d['oracle_name'] = 'maria'
with open('./data.json', 'w') as f:
json.dump(d, f, indent=4)
I have a text file named 'triple_response.txt' which contain the some text as :
(1,(db_name,string),DSP)
(1,(rel, id),2)
(2,(rel_name, string),DataSource)
(2,(tuple, id),201)
(2,(tuple, id),202)
(2,(tuple, id),203)
(201,(src_id,varchar),Pos201510070)
(201,(src_name,varchar),Postgres)
(201,(password,varchar),root)
(201,(host,varchar),localhost)
(201,(created_date,date),2015-10-07)
(201,(user_name,varchar),postgres)
(201,(src_type,varchar),Structured)
(201,(db_name,varchar),postgres)
(201,(port,numeric),None)
(202,(src_id,varchar),pos201510060)
(202,(src_name,varchar),Postgres)
(202,(password,varchar),root)
(202,(host,varchar),localhost)
(202,(created_date,date),2015-10-06)
(202,(user_name,varchar),postgres)
(202,(src_type,varchar),Structured)
(202,(db_name,varchar),DSP)
(202,(port,numeric),5432)
(203,(src_id,varchar),pos201510060)
(203,(src_name,varchar),Postgres)
(203,(password,varchar),root)
(203,(host,varchar),localhost)
(203,(created_date,date),2015-10-06)
(203,(user_name,varchar),postgres)
(203,(src_type,varchar),Structured)
(203,(db_name,varchar),maindb)
(203,(port,numeric),5432)
I am trying to convert these contents into JSON using a python script:
import re
import collections
import json, jsonpickle
def convertToJSON(File):
word_list=[]
row_list = []
try:
with open(File,'r') as f:
for word in f:
word_list.append(word)
with open(File,'r+') as f:
for row in f:
print row
row_list.append(row.split())
column_list = zip(*row_list)
except IOError:
print "Error in opening file.."
triple =""
for t in word_list:
triple+=t
tripleList = re.findall(r"\([^\(^\)]*\)",triple)
idList = re.split(r"\([^\(^\)]*\)",triple)
i =0
jsonDummy = []
jsonData = {}
for trip in tripleList:
nameAndType = re.split(r",|:",trip)
if(i==0):
key = re.compile("[^\w']|_").sub("",idList[i])
else:
try:
key = re.compile("[^\w']|_").sub("",idList[i].split("(")[1])
except IndexError:
pass
i = i+1
if(idList[i].find('(')!=-1):
try:
content = re.compile("[^\w']|_").sub("",idList[i].split(")")[0])
except IndexError:
pass
else:
content = re.compile("[^\w']|_").sub("",idList[i])
try:
trip = trip[1:-1]
tripKey = trip[1]
except IndexError:
tripKey = ''
name = re.compile("[^\w']").sub("",nameAndType[0])
try:
typeName = re.compile("[^\w']|_").sub("",nameAndType[1])
except IndexError:
typeName = 'String'
tripDict = dict()
value = dict()
value[name] = content
tripDict[key]=value
jsonDummy.append(tripDict)
for j in jsonDummy:
for k,v in j.iteritems():
jsonData.setdefault(k, []).append(v)
data = dict()
data['data'] = jsonData
obj = {}
obj=jsonpickle.encode(data, unpicklable=False)
return obj
pass
I am calling this function convertToJSON() within the same file as:
print convertToJSON("triple_response.txt")
I am getting the output as i expect like:
{"data": {"1": [{"db_name": "DSP"}, {"rel": "2"}], "201": [{"src_id": "Pos201510070"}, {"src_name": "Postgres"}, {"password": "root"}, {"host": "localhost"}, {"created_date": "20151007"}, {"user_name": "postgres"}, {"src_type": "Structured"}, {"db_name": "postgres"}, {"port": "None"}], "203": [{"src_id": "pos201510060"}, {"src_name": "Postgres"}, {"password": "root"}, {"host": "localhost"}, {"created_date": "20151006"}, {"user_name": "postgres"}, {"src_type": "Structured"}, {"db_name": "maindb"}, {"port": "5432"}], "2": [{"rel_name": "DataSource"}, {"tuple": "201"}, {"tuple": "202"}, {"tuple": "203"}], "202": [{"src_id": "pos201510060"}, {"src_name": "Postgres"}, {"password": "root"}, {"host": "localhost"}, {"created_date": "20151006"}, {"user_name": "postgres"}, {"src_type": "Structured"}, {"db_name": "DSP"}, {"port": "5432"}]}}
Now the problem which i am facing, which i am calling this from the outside the class as:
def extractConvertData(self):
triple_response = SPO(source, db_name, table_name, response)
try:
_triple_file = open('triple_response.txt','w+')
_triple_file.write(triple_response)
print "written data in file.."
with open('triple_response.txt','r+') as f:
for word in f:
print word
jsonData = convertToJSON(str('triple_response.txt'))
except IOError:
print "Not able to open a file"
print "Converted into JSON"
print jsonData
pass
The same code of convertToJSON() is not working...
It neither giving any output nor giving any error, it is not able to read the content from the 'triple_response.txt' file in the line.
with open('triple_response.txt','r+') as f:
for word in f:
print word
Any one can tell me solution to this problem..
_triple_file is never closed (except implicitly when you end the Python process, which is a terrible practice).
You can get platform-specific behavior when you have dangling filehandles like that (what is your platform? Unix? Windows?). Probably the write to _triple_file is not getting flushed.
So don't leave it dangling. Make sure to close it after you write it: (_triple_file.write(triple_response)). And in fact then assert that that file length is non-zero, using os.stat(), otherwise raise an Exception.
Also, you only have one big try...except clause to catch all errors, this is too much in one bite. Break it into two separate try...except clauses for writing _triple_file, and then reading it back. (Btw you might like to use tempfile library instead, to sidestep needing to know your intermediate file's pathname).
Something like the following untested pseudocode:
triple_response = SPO(source, db_name, table_name, response)
try:
_triple_file = open('triple_response.txt','w+')
_triple_file.write(triple_response)
_triple_file.close()
except IOError:
print "Not able to write intermediate JSON file"
raise
assert [suitable expression involving os.stat('triple_response.txt') to test size > 0 ], "Error: intermediate JSON file was empty"
try:
with open('triple_response.txt','r+') as f:
for word in f:
print word
jsonData = convertToJSON(str('triple_response.txt'))
except IOError:
print "Not able to read back intermediate JSON file"
#raise # if you want to reraise the exception
...