I have a function:
def save(path,data):
file = open(path,'w',encoding='utf-8')
file.write(json.dumps(data))
file.close()
It saves the file, but without tabbing. Everything goes in one line.
save('1.json',{"1":"222"})
How do I make it save in tab format?
{
"1":"222"
}
Use indent argument with json.dumps as below:
import json
def save(path, data):
file = open(path,'w',encoding='utf-8')
file.write(json.dumps(data, indent=4))
file.close()
save('1.json',{"1":"222"})
json.dumps have an indent keyword argument to specify the indentation of the output.
def save(path, data, indent=2):
file = open(path,'w',encoding='utf-8')
file.write(json.dumps(data, indent=indent))
file.close()
save('1.json',{"1":"222"})
1.json
{
"1": "222"
}
use params indent
def save(path,data):
with open(path,'w',encoding='utf-8') as f:
f.write(json.dumps(data,indent=4))
Related
I have a code that needs to read a JSON file with multiple lines, i.e:
{"c1-line1": "value", "c2-line1": "value"}
{"c1-line2": "value", "c2-line2": "value"}...
and, after change the keys values (already working), I need to write a new json file with these multiple lines, i.e:
{"newc1-line1": "value", "newc2-line1": "value"}
{"newc1-line2": "value", "newc2-line2": "value"}...
My problem is that my code are just writing the last value readed:
{"newc1-line2": "value", "newc2-line2": "value"}
My code:
def main():
... # changeKeyValueCode
writeFile(data)
def writeFile(data):
with open('new_file.json', 'w') as f:
json.dump(data, f)
I already tried with json.dumps and just f.write('') or f.write('\n')
I know that data in writeFile() is correctly with each line value.
How can I resolve this, please?
def main():
... # changeKeyValueCode
writeFile(data)
def writeFile(data):
with open('new_file.json', 'a') as f:
json.dump(data, f)
with open('new_file.json', 'a')
open file with (a), it will search the file if found append data to the end, else it will create empty file and then append data.
I was working on a piece of code that reads a json file ever second or so in accordance with a pyqt5 graph. This was my code:
import csv
from getmac import get_mac_address as gma
import time
macaddr = gma()
mac_name = macaddr.replace(":", "")
weathersensor_id = "BME20"
rainsensor_id = "GCCG41"
def readJSONLatestAllMQTT():
with open(f"{mac_name}_{weathersensor_id}.json", "r") as myfile:
dataRead = json.load(myfile)
time.sleep(0.01)
return dataRead, True
When I went to access an element of the json file by doing something like print(dataRead["Temperature"]), I got an error message that said that dataRead was being output as a string, not a dict/json file like I intented. How would I go about turning dataRead into a dict instead of a string?
Here is the json file for some background:
"{\"dateTime\": \"2021-06-18 07:47:33.710631\", \"Temperature\": 69.26586754195563, \"Pressure\": 346.63102628054014, \"Humidity\": 80.54066707990641, \"Altitude\": 125.3640651860123}"
I believe you are having this problem because your json file is a string instead of a dictionary, I think it should be:
{"dateTime": "2021-06-18 07:47:33.710631", "Temperature": 69.26586754195563, "Pressure": 346.63102628054014, "Humidity": 80.54066707990641, "Altitude": 125.3640651860123}
instead of:
"{\"dateTime\": \"2021-06-18 07:47:33.710631\", \"Temperature\": 69.26586754195563, \"Pressure\": 346.63102628054014, \"Humidity\": 80.54066707990641, \"Altitude\": 125.3640651860123}"
I made a program in python3 that writes to json upon input from user. Program is running but includes slashes
i want it to be
Output:(written to a file sample.json)
{
"api" : api_key=4ewrs5798hoknlkmnnmhbvjgfd7"
}
But instead i get
Output:(written to a file sample.json)
{\"api\":\"api_key=4ewrs5798hoknlkmnnmhbvjgfd7\"}"
Backslash appears at every (") also indents are missing even if declared or not
import json
k1 = input("enter key")
k2 ='{"api" : ""api_key='+k1+'"}'
with open("sample.json", "w") as outfile:
json.dump(k2, outfile, indent=4)
print("success")
The problem has to do with the quotations you are using in k2. A better way of doing this is to use dicts.
import json
k2 = {}
k2['api'] = "api_key=" + input("enter key")
with open("sample.json", "w") as outfile:
json.dump(k2, outfile, indent=4)
print("success")
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 am using the following function to get json from the flickr API. The string it returns is a properly formatted chunk of JSON:
def get_photo_data(photo_id):
para = {}
para["photo_id"] = photo_id
para["method"] = "flickr.photos.getInfo"
para["format"] = "json"
para["api_key"] = FLICKR_KEY
request_data = params_unique_combination("https://api.flickr.com/services/rest/", para)
if request_data in CACHE_DICTION:
return CACHE_DICTION[request_data]
else:
response = requests.get("https://api.flickr.com/services/rest/", para)
CACHE_DICTION[request_data] = response.text[14:-1]
cache_file = open(CACHE_FNAME, 'w')
cache_file.write(json.dumps(CACHE_DICTION))
cache_file.close()
return response.text[14:-1]
The issue I am having is that when I go to write the json to my cache file it keeps adding in backslashes, like this example:
"https://api.flickr.com/services/rest/format-json_method-flickr.photos.getInfo_photo_id-34869402493": "{\"photo\":{\"id\":\"34869402493\",\"secret\":\"56fcf0342c\",\"server\":\"4057\",\"farm\":5,\"dateuploaded\":\"1499030213\",\"isfavorite\":0,\"license\":\"0\",\"safety_level\":\"0\",\"rotation\":0,\"originalsecret\":\"c4d1d316ed\",\"originalformat\":\"jpg\",\"owner\":{\"nsid\":\"150544082#N05\",\"username\":\"ankitrana_\",\"realname\":\"Ankit Rana\",\"location\":\"Cincinnati, USA\",\"iconserver\":\"4236\",\"iconfarm\":5,\"path_alias\":\"ankitrana_\"},\"title\":{\"_content\":\"7\"},\"description\":{\"_content\":\"\"},\"visibility\":{\"ispublic\":1,\"isfriend\":0,\"isfamily\":0},\"dates\":{\"posted\":\"1499030213\",\"taken\":\"2017-06-19 13:43:38\",\"takengranularity\":\"0\",\"takenunknown\":\"0\",\"lastupdate\":\"1499041020\"},\"views\":\"41\",\"editability\":{\"cancomment\":0,\"canaddmeta\":0},\"publiceditability\":{\"cancomment\":1,\"canaddmeta\":0},\"usage\":{\"candownload\":1,\"canblog\":0,\"canprint\":0,\"canshare\":1},\"comments\":{\"_content\":\"0\"},\"notes\":{\"note\":[]},\"people\":{\"haspeople\":0},\"tags\":{\"tag\":[{\"id\":\"150538742-34869402493-5630\",\"author\":\"150544082#N05\",\"authorname\":\"ankitrana_\",\"raw\":\"cincinnati\",\"_content\":\"cincinnati\",\"machine_tag\":0},{\"id\":\"150538742-34869402493-226\",\"author\":\"150544082#N05\",\"authorname\":\"ankitrana_\",\"raw\":\"ohio\",\"_content\":\"ohio\",\"machine_tag\":false},
... etc., etc.}
How can I store the JSON to the existing file without these additional \ characters, as it is represented when I print the string?
use your_string.decode('string_escape') to unescape \" to "
update:
your string escaped because json.dumps(), it convert object to string and later you can read it using json.loads(), the result are unescaped.
you can save it without slash using str()
cache_file.write(str(CACHE_DICTION))
# {'myparam' :'"162000","photo":...'
but the problem it save to file with single quotes, it not valid json and not compatible with json.loads()
my suggestion keep your code as above, except you want to store it to file CACHE_FNAME.json
cache_file = open(CACHE_FNAME, 'w')
cache_file.write(response.text)
cache_file.close()
# {"photos":{"page":1,"pages":6478,..}
You could try replacing the "\" with the str.replace function in python
Add the code after the following line
cache_file = open(CACHE_FNAME, 'w')
json_item = str(json.dumps(CACHE_DICTION))
json_item.replace("\", "")
and change this line
cache_file.write(json.dumps(CACHE_DICTION))
to
cache_file.write(json_item)
let me know if this works for you
just replace \ with a whitespace.
I did the same thing while i was working with JSON.
json_new = json.replace('\\', '')