How to add to a json file in python - 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"
}
}
}

Related

Handling keys inside a key from .json file

I am trying to print an specific key from a JSON file without success.
.json file is:
{
"testing": [
{
"_name": "teste",
"_profile_telphone": "212331233",
"_age": "21"
}
]
}
the function I'm using is:
def load(self):
filename = self.profile_entry.get()
if filename == "":
msg = "Insert a profile name"
messagebox.showinfo("Profile name is empty", msg)
self.profile_entry.focus()
else:
with open('profile_'+filename+'.json', 'r') as outfile:
data = json.load(outfile)
print(data[filename])
outfile.close()
with print(data[filename]) I can print entire
{
"_name": "teste",
"_profile_telphone": "212331233",
"_age": "21"
}
But how can I print only name or age for example?
data is a list of JSONs - you have a json array there, in order to parse it you can do it with a for statement
for element in data[filename]:
print(element[‘_name’])
print(element[‘_profile_telphone’])
print(element[‘_age’])

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
}
}
]
}

JSON file not reading

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/

how to open the json file using python?

ENG_RequestData.json:
{
"appKey": "9c9fa7201e90d3d96718bc3f36ce4cfe1781f2e82f4e5792996623b3b474fee2c77699eb5354f2136063e1ff19c378f0f6dd984471a38ca5c393801bffb062d6",
"appId": "NMDPTRIAL_AutomotiveTesting_NCS61HTTP",
"uId": "Alexander",
"inCodec": "PCM_16_8K",
"outCodec": "PCM_16_8K",
"cmdName": "NVC_TTS_CMD",
"appName": "Python",
"appVersion": "1",
"language": "eng-GB",
"carrier": "carrier",
"deviceModel": "deviceModel",
"cmdDict": {
"tts_voice": "Serena",
"tts_language": "eng-GB",
"locale": "canada",
"application_name": "Testing Python Script",
"organization_id": "NUANCE",
"phone_OS": "4.0",
"phone_network": "wifi",
"audio_source": "SpeakerAndMicrophone",
"location": "47.4925, 19.0513",
"application_session_id": "1234567890",
"utterance_number": "5",
"ui_langugage": "en",
"phone_submodel": "nmPhone2,1",
"application_state_id": "45"
}
}
CODE :
print LNG // it is printing as ENG
ENG_RequestDataFile = scriptPath + "\\" + "ENG_RequestData.json"
print ENG_RequestDataFile // it is printing as C:\Users\\Desktop\OWN\2016_02_11\ENG_RequestData.json
DEU_RequestDataFile = scriptPath + "\\" + "DEU_RequestData.json"
try:
if LNG == 'ENG':
with open(ENG_RequestDataFile) as json_file:
print json_file
JSON_ENGData = json.load(json_file)
print JSON_ENGData
elif LNG == 'DEU':
with open(DEU_RequestDataFile) as json1_file:
JSON_DEUData = json.load(json1_file)
else:
print ("No Other Language")
except:
print ("[ERROR] Cannot open the Request data file")
I am reading a json file from the specific path and the json file is as shown above. there are two json files for one english and german but I am trying to read, but it is printing as [ERROR] Cannot open the Request data file. I am not able to open it. can someone tell me how ?
Try this code:
import json
#Path you posted
path = os.path.join('C:'+os.sep+'Users'+os.sep+'Desktop'
+os.sep+'OWN'+os.sep+'2016_02_11'
+os.sep+'ENG_RequestData.json')
def get_tts(LNG,filename):
try:
if LNG == 'ENG':
with open(filename) as json_file:
JSON_ENGData = json.load(json_file)
print(JSON_ENGData)
elif LNG == 'DEU':
with open(DEU_RequestDataFile) as json_file:
JSON_DEUData = json.load(json_file)
else:
print("No Other Language")
except:
print("[ERROR] Cannot open the Request data file")
#Execute the function
get_tts('ENG',path)
More information here:
https://stackoverflow.com/a/2422864/5915424

Adding json object to unnamed set of json objections

I have here a set of json objects.
[
{
"group": "GroupName1",
"name": "Name1",
"nick": "Nick1",
"host": "Hostname1",
"user": "user1",
"sshport": "22",
"httpport": "80"
},
{
"group": "GroupName2",
"name": "Name2",
"nick": "Nick2",
"host": "hostname2",
"user": "user2",
"sshport": "22",
"httpport": "80"
}
]
I have a CLI script taking raw_input and building a new dict object containing the new object parameters as such:
def main():
# CLI Input
group_in = raw_input("Group: ")
name_in = raw_input("Name: ")
nick_in = raw_input("Nick: ")
host_in = raw_input("Host: ")
user_in = raw_input("User: ")
sshport_in = raw_input("SSH Port: ")
httpport_in = raw_input("HTTP Port: ")
# New server to add
jdict = {
"group": group_in,
"name": name_in,
"nick": nick_in,
"host": host_in,
"user": user_in,
"sshport": sshport_in,
"httpport": httpport_in
}
Assuming json file containing the aforementioned json objects formatted as such is loaded as:
with open(JSON_PATH, mode='r') as rf:
jf = json.load(rf)
I know how to do this by hacking the file using readlines/writelines, but how would I add jdict in at the end of jf pythonically so I can just write the file back with the complete new set of objects formatted in the same way?
jf is now just a Python list, so you can append the new dictionary to your list:
jf.append(jdict)
then write out the whole object back to your file, replacing the old JSON string:
with open(JSON_PATH, mode='w') as wf:
json.dump(jf, wf)

Categories