how to open the json file using python? - 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

Related

How to add file not found function on my script when csv file is not existing on the path

Would like to add an print statement which triggers when the csv file is not existing on directory, May I know what I need to add on my script?
SPREADSHEET_ID = 'SAMPLE_SPREADSHEETI1234'
worksheet_name = 'CSVimport'
credentials = 'pdkey123.json'
for my_csv in glob.glob('/home/pdadmin/MYProject.csv':
print ('CSV file found!')
print (my_csv)
Export script
def export_csv(my_csv, sheet_id):
with open(my_csv, 'r') as csv_file:
csvContents = csv_file.read()
body = {
'requests': [{
'pasteData': {
"coordinate": {
"sheetId": sheet_id,
"rowIndex": "0",
"columnIndex": "0",
},
"data": csvContents,
"type": 'PASTE_NORMAL',
"delimiter": ',',
You can use os utilities.
Here's the code you asked for:
import glob
import os
def export_csv(my_csv, sheet_id):
if os.path.exists(my_csv):
with open(my_csv, 'r') as csv_file:
csvContents = csv_file.read()
body = {
'requests': [{'pasteData': {
"coordinate": {
"sheetId": sheet_id,
"rowIndex": "0",
"columnIndex": "0",
},
"data": csvContents,
"type": 'PASTE_NORMAL',
"delimiter": ','
}}]
}
# ... SUCCESS_TRIGGER
#
print(body)
else:
# ... FILE_NOT_FOUND_TRIGGER
raise FileNotFoundError()
SPREADSHEET_ID = 'SAMPLE_SPREADSHEETI1234'
worksheet_name = 'CSVimport'
credentials = 'pdkey123.json'
for my_csv in glob.glob('/home/pdadmin/MYProject.csv'):
try:
export_csv(my_csv, 1)
print('CSV file found!')
except FileNotFoundError:
print('CSV file NOT found!')
The issue when using for in loop in this case is that when it doesn't match anything (file not existing), it won't proceed as the returned list would be empty. You could check first if the returned list is not empty. If it is not empty, then process your data, else, print something.
Once in the for in, we are sure all files are present as glob.glob will match only existing files.
import os
import glob
SPREADSHEET_ID = 'SAMPLE_SPREADSHEETI1234'
worksheet_name = 'CSVimport'
credentials = 'pdkey123.json'
path = '/home/pdadmin/MYProject.csv';
if len(csv_list := glob.glob(path)):
for my_csv in csv_list:
print(f"{my_csv} file found!")
export_csv(my_csv, SPREADSHEET_ID)
else:
print(f"{path} not found!")
You can also modify the path to use a pattern so it catches multiple files and export them one by one. Just add an asterisk as wildcard within the path.

How to read a .json file in pandas to export it as a readable .csv file

I have created a .json file by appending a number of json strings using a get request. My aim is to convert the appended .json file into a readable .csv file. The .json file has the following format:
[{
"trades":[
{
"id": 20995465,
"unique_identifier": null,
"transaction_type": "BUY",
"transaction_date": "2016-11-08",
"symbol": "RDSA",
"market": "LSE",
"quantity": 10,
"price": 20.84,
"exchange_rate": 0.5525,
"brokerage": 3.619909502,
"brokerage_currency_code": "GBP",
"value": 380.81,
"comments": null,
"portfolio_id": 293304,
"holding_id": 6258682,
"instrument_id": 32021,
"confirmed": true,
"links": {
"portfolio": "https://api.sharesight.com/api/v3/portfolios/293304"
}
}
],
"links":{
"self":"https://api.sharesight.com/api/v3/portfolios/2/trades"
}
},
{
"trades":[
{
"id": 20995425,
"unique_identifier": null,
"transaction_type": "BUY",
"transaction_date": "2018-11-08",
"symbol": "PDSA",
"market": "LSE",
"quantity": 1,
"price": 2.84,
"exchange_rate": 0.25,
"brokerage": 7.619909502,
"brokerage_currency_code": "GBP",
"value": 80.81,
"comments": null,
"portfolio_id": 293604,
"holding_id": 6258635,
"instrument_id": 32023,
"confirmed": true,
"links": {
"portfolio": "https://api.sharesight.com/api/v3/portfolios/293604"
}
}
],
"links":{
"self":"https://api.sharesight.com/api/v3/portfolios/2/trades"
}
}
]
My attempt
client_id = 'ClientID'
client_secret = 'ClientSecret'
access_token_url='https://api.sharesight.com/oauth2/token'
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=access_token_url, client_id=client_id, client_secret=client_secret)
access_token = token['access_token']
head = {'Authorization': f'Bearer {access_token}'}
# Get the portfolios
r = requests.get('https://api.sharesight.com/api/v2/portfolios.json', headers=head)
# print(r)
j = r.json()
# print(j)
rjs = []
for p in j['portfolios']:
# print(p)
name = p['name']
pid = p['id']
print(f'Retrieving {name} - {pid}')
vurl = f'https://api.sharesight.com/api/v2/portfolios/{pid}/trades.json'
r = requests.get(vurl, headers=head)
rj = r.json()
rjs.append(rj)
with open('/Users/Filename.json', 'w') as json_file:
json.dump(rjs, json_file)
# Opening JSON file and loading the data
# into the variable data
with open('/Users/Filename.json') as json_file:
data = json.load(json_file)
trades_data = data['trades']
# now we will open a file for writing - create a blank .csv file
data_file = open('/Users/Filename.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for emp in trades_data:
if count == 0:
# Writing headers of CSV file
header = emp.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(emp.values())
data_file.close()
Error Code
trades_data = data['trades']
TypeError: list indices must be integers or slices, not str
I think I get this error because 'trades' is replicated twice in my .json string and thus might be viewed as a string. Is there a workaround around this issue? I'm new to python so would greatly appreciate your help!
Desired Output
A .csv file with the following structure:
Answer by #dsillman2000 for entry in data: trades_data = entry['trades'] ... etc

Modify a sub value of json file using python

I'm trying to create multiple JSON files with different numbers at specific value, this is my code :
import json
json_dict = {
"assetName": "GhostCastle#",
"previewImageNft": {
"mime_Type": "png",
"description": "#",
"fileFromIPFS": "QmNuFreEoJy9CHhXchxaDAwuFXPHu84KYWY9U7S2banxFS/#.png",
"metadataPlaceholder": [
{
"": ""
}
]
}
}
n = 10
for i in range(1, n+1):
json_dict["assetName"] = f"GhostCastle{i}"
json_dict[#What to put here to choose "fileFromIPFS"] = f"QmNuFreEoJy9CHhXchxaDAwuFXPHu84KYWY9U7S2banxFS/{i}.png"
with open(f"{i}.json", 'w') as json_file:
#json.dump() method save dict json to file
json.dump(json_dict, json_file)
so What to put to choose "fileFromIPFS" in the second json_dict

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’])

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

Categories