JSON file not reading - python

import json
import io
username = input('Enter your username ') #Input
password = input('Now enter your password ') #Input
usernamelow = username.lower()
username input converts to lowercase
auth = {
"users": usernamelow,
"pass": password
}
the JSON string that is writ to the JSON file
dump = json.dumps(auth) #Gathers data
print (dump) #Debug print
with open('auth.json', 'a') as outfile:
for line in outfile:
json.dump(auth, outfile, indent=4)
(Dumps AUTH)
adds data to the JSON file ^
with open('auth.json', 'r') as f:
data = json.load(f)
Basically this is a school project I'm working on and when I append to the file more than once it gives me an extra data error. This is the JSON that appears when the script is ran:
{
"pass": "testpass",
"users": "testuser"
}{
"users": "testinguser",
"pass": "testingpass"
}
I appear to get this error:
ValueError: Extra data: line 4 column 2 - line 7 column 2 (char 52 -
110)

Okay so the following error tells us something:-
ValueError: Extra data
The data you're trying to load is not properly formatted in JSON. The correct JSON formatting would be:-
[{
"pass": "testpass",
"users": "testuser"
}, {
"users": "testinguser",
"pass": "testingpass"
}]
A better practice would be to input all the data once in a list of dicts, and then you can dump it into the file as a whole:-
with open('auth.json', 'a') as outfile:
json.dump(auth_list, outfile, indent=4)

The error might be the missing comma between the entries
Another way is, first to collect all existing data from your file in a list (of dictionaries) and then append the new input. this might be usefull for checks of duplicates
import json
import os
auth_list = []
file_name = 'auth.json'
if os.path.isfile(file_name):
with open(file_name, 'r') as f:
auth_list = json.load(f)
print(auth_list)
username = input('Enter your username ')
password = input('Now enter your password ')
usernamelow = username.lower()
auth = {
"users": usernamelow,
"pass": password
}
auth_list.append(auth)
with open(file_name, 'w') as outfile:
json.dump(auth_list, outfile)
This might be also a usefull ressource https://realpython.com/python-json/

Related

How do i append at a json file at the end of the list with python

So i want to put some json strings like this
[{"username": "username", "key": "key"}, {"username": "username", "key": "key"}, ...]
i tried json.dump and json.dumps but it doesn't worked for me, please help me
this is the code that i written for now:
import json
username = input('Username to put in the keys file: ')
key = input('Key to put in the keys file: ')
uak = {"username": username, "key": key}
with open('keys.json', 'r') as r:
data = json.load(r)
with open('keys.json', 'w') as w:
json.dump(data, w)
Your keys.json file's content initially must be equal to [] that matchs an empty json array to append your objects at runtime, then you have to add your {"username": username, "key": key} json object to your data list with the append method like below:
#keys.json is initialized with []
import json
username = input('Username to put in the keys file: ')
key = input('Key to put in the keys file: ')
uak = {"username": username, "key": key}
with open('keys.json', 'r') as r:
data = json.load(r)
with open('keys.json', 'w') as w:
data.append(uak)
json.dump(data, w)

How to get rid of extra curly braces in JSON?

I'm basically creating a contact book, and I want to do it storing data on JSON to practice it. I have sort a code that allows it from a dictionary, but the problem is that when I rerun the script, another dictionary is appended into the existing one, creating a couple of extra braces which throws the error "End of file expected."
This is the code:
import json
new_contacts = {}
def contacts():
while True:
name = input("Contact's name: ")
email = input("Email: ")
number = input("Phone number: ")
new_contacts[name] = {"email": email, "number": number}
"""cursor.execute(
'INSERT INTO contacts VALUES (?, ?, ?)',
(name, email, number)
)"""
restart_or_not = input("Continue? y/n ").lower()
if restart_or_not == "y":
print(new_contacts)
continue
else:
with open('contact_book.json', 'a') as file:
json.dump(new_contacts, file, indent=4)
break
contacts()
And this is a sample of a JSON that comes out from it:
{
"d": {
"email": "e",
"number": "3"
},
"h": {
"email": "y",
"number": "6"
},
"f": {
"email": "r",
"number": "3"
},
"n": {
"email": "j",
"number": "9"
}
}{
"g": {
"email": "j",
"number": "0"
}
}
The first four entries don't create any problem because they are appended in the same run, but if I quit the program and rerun it (example "g") then the new dictionary creates the conflict. Any tips?
One way of doing it, is before adding to the file, you delete the last closing bracket } and before dumping, you cast your dict into a string and remove the first bracket using this your_string[1:].
The other way which I coded for you, is you load the json into a variable, add the new inputs and then re dump it into the file
import json
from os import path # it helps to check if file exists
new_contacts = {}
def contacts():
while True:
name = input("Contact's name: ")
email = input("Email: ")
number = input("Phone number: ")
new_contacts[name] = {"email": email, "number": number}
"""cursor.execute(
'INSERT INTO contacts VALUES (?, ?, ?)',
(name, email, number)
)"""
restart_or_not = input("Continue? y/n ").lower()
if restart_or_not == "y":
print(new_contacts)
continue
else:
# if the file doesn't exist, write an empty json object into it
# which will make it easier later to load data from
if not path.exists('contact_book.json'):
with open('contact_book.json', 'w+') as file:
json.dump({}, file)
# This loads the data into the variable dict called loaded_data
with open('contact_book.json', 'r') as file:
loaded_data = json.load(file)
for k, v in new_contacts.items():
loaded_data[k] = v
# redumps your data into the json file
with open('contact_book.json', 'w') as file:
json.dump(loaded_data, file, indent=4)
break
contacts()
Just updated a bit of the else part of your code. It checks whether a file exists or not. If it exists, the contents of the file is read and updated and then dumped into the file. If it doesn't exist, your old code will be executing.
if os.stat("contact_book.json").st_size != 0:
with open('contact_book.json', 'r+') as file:
contents = json.loads(file.read())
contents.update(new_contacts)
file.seek(0)
json.dump(contents, file, indent=4)
else:
with open('contact_book.json', 'a') as file:
json.dump(new_contacts, file, indent=4)
break
Honestly, not an efficient solution. But this should be able to invoke an idea.

Search .txt file for a specific word and print data following that word

I am new to python so hear me out. I have been looking all over and can't find how to specifically do what I need. I request weather information from a website and then I convert it to a .txt file. I want to print the value next to the word I search. See below for an excerpt from .txt file:
{"cod": "200", "message": 0.004, "cnt": 10, "list": [{"dt": 1548698400, "main": {"temp": 275.32, "temp_min": 274.915, "temp_max": 275.32,
I want to search for temp and have it print 275.32.
Added my code | API key has been removed | words related to "test" are play around variable to see if an output changes
import requests
import re
import time
import json
from datetime import datetime, timedelta
curDate=datetime.now().timestamp()
print(datetime.utcfromtimestamp(curDate).strftime('%Y-%m-%d %H:%M:%S'))
system = True
while system:
userInput=input("Type exit to leave or enter your city of choice: ")
findExit = re.search(r'xit', userInput)
findTheExit = re.search(r'XIT', userInput)
if str(findExit)=='None' and str(findTheExit)=='None':
weatherInfo = requests.get('https://api.openweathermap.org/data/2.5/forecast?q='+userInput+',us&appid=api_key_here&cnt=10')
test = weatherInfo.json()
testTwo = json.dumps(test)
info=json.loads(testTwo)
with open("Data.txt", "a") as outfile:
json.dump(test, outfile)
# Yassine Addi code added
with open('Data.txt', 'r') as fp:
data = json.load(fp)
for item in data['list']:
print(item['main']['temp'])
# Yassine Addi end
else:
print("System turning off, goodbye")
system=False
if your file is a valid JSON, then do this
import json
with open('a.txt', 'r') as fp:
data = json.load(fp)
for item in data['list']:
print(item['main']['temp']) # prints 275.32
considering that a.txt contains
{
"cod": "200",
"message": 0.004,
"cnt": 10,
"list": [
{
"dt": 1548698400,
"main": {
"temp": 275.32,
"temp_min": 274.915,
"temp_max": 275.32
}
}
]
}

How to add to a json file in python

I can read the json file and set the information I need to the variables. I have accounts, and I need to be able to add an account to it, this is the code I have so far:
import json
user = raw_input("User: ")
with open('text.json') as data_file:
data = json.load(data_file)
code = data["users"][user]["pass"]
display = data["users"][user]["display"]
print "Password: " + code
print "Display Name - " + display
This works fine to read the file, here is the expected format of the output json file:
{
"users":{
"User1": {
"display": "User1",
"pass": "EzPass123"
},
"Richard": {
"display": "Attack69",
"pass": "Smith"
}
}
}
Can someone show me how to add another account to the accounts already existing in the dictionary?
import json
# here you read your new user and his password
user = raw_input("User: ")
display = raw_input("Display name: ")
pwd = raw_input("Pass: ")
with open('text.json') as data_file:
data = json.load(data_file)
# update the data dictionary then re-dump it in the file
data['users'].update({
user: {
'display': display,
'pass': pwd
}
})
with open('text.json', 'w') as data_file:
json.dumps(data, data_file, indent=4)
Here's a solution covering the fixes discussed in the other answer:
#!python2
import json
# here you read your new user and his password
user = raw_input("User: ")
display = raw_input("Display name: ")
pwd = raw_input("Pass: ")
with open('text.json') as data_file:
data = json.load(data_file)
data['users'][user] = {'display':display,'pass':pwd}
with open('text.json','w') as data_file:
json.dump(data, data_file, indent=4)
Output:
User: markt
Display name: Mark
Pass: 123
Result:
{
"users": {
"markt": {
"display": "Mark",
"pass": "123"
},
"Richard": {
"display": "Attack69",
"pass": "Smith"
},
"User1": {
"display": "User1",
"pass": "EzPass123"
}
}
}

Python - write/ADD a new record in file with Json format

I want to add a new record at the end of my file Json, For now it contains
{
"1":
{
"coef":987,
"Term":
{
"x1":6,"x2":0,"x3":8
}
}
}
im reading this file like this :
try:
json_data=open ("/home/sage/content.txt")
data=json.load (json_data)
except IOError:
print "Can't open your file"
how to add a new record at the end of file.
After reading the data , you can't add to the file, you need to create a new file (with the same name if you want):
data['added_data'] = 'some data added'
write_file = open("/home/sage/content.txt", "w")
write_file.write(json.dumps(data))
If you are using python 2.5 or newer you should use with statement dealing with files:
import json
with open('content.txt', 'r') as f:
data = json.load(f)
data["2"] = {
"coef":987,
"Term":
{
"x1":6,"x2":0,"x3":8
}
}
with open('content.txt', 'w') as f:
json.dump(data, f)

Categories