I'm still learning python, and I'm writing a classic password manager app. It uses an external JSON file to store the data:
{
"info": [
{
"website_url": "1",
"username": "1",
"password": "1"
},
{
"website_url": "2",
"username": "2",
"password": "2"
},
{
"website_url": "3",
"username": "3",
"password": "3"
},
{
"website_url": "4",
"username": "4",
"password": "4"
}
]
}
I want to add an option to delete login information from the file, but I don't really know what to do right now. Here's my code for the feature (I'm using the JSON library):
url = input('Paste Login Page URL Here : ')
with open(INFO_PATH) as file:
data = json.load(file)
for info in data['info']:
if info['website_url'] == url:
del info
Any ideas?
You have to deserialize your json file to a Python object, delete the entry from it and after serialize the object to the same file, so rewriting the content. In your case you json file does not coincide with a json array but it is an json object that contains a json array labelled with "info", so you have to extract this field from it. This can be done like below:
import json
url = input('Paste Login Page URL Here : ')
with open(INFO_PATH, 'r') as file:
data = json.load(file)['info'] #data coincides with the json info array
data = [info for info in data if info['website_url'] != url]
#overwrite the json file content with the new data
with open(INFO_PATH, 'w') as file:
json.dump({'info': data}, file)
Related
Wondering if it is possible to take a json file such as:
[
{
"firstName": "John",
"lastName": "Doe",
"dob": "1900-01-01",
"zipCode": "12345",
"subscriberId": "123456789",
"policyNumber": "12345"
},
{
"firstName": "Jane",
"lastName": "Doe",
"dob": "1900-01-01",
"zipCode": "54321",
"subscriberId": "987654321",
"policyNumber": "54321"
}
]
& looping over that data to call to the API.
The shell script that I'm using to make one call to the API looks like this:
#!/bin/bash
# Rally Forwarder Keys
clientkey=test
apikey=test
#SET apikey=test
# Public URL
url="test"
curl -v -X POST -d '{"firstName":"test","lastName":"test","dob":"1900-01-01","zipCode":"12345","subscriberId":"123456789","policyNumber":"12345"}' -H "Content-type:application/json" "${url}" -H "X-OnePass-API-Key: ${apikey}" -H "X-OnePass-ClientKey: ${clientkey}"
I run a check for eligible members and have a list of about 700 that I really don't want to copy & paste and then manually edit the data for each call.
My original code is in VBA Selenium which does not work with the API. It originally went to a website, used the data to fill in a form and submitted the form to grab the code. My shell scripting skills are still pretty basic or would python work better for this?
Well use json and requests packages as follows :
import json
import requests
# Setup
API_KEY = ...
CLIENT_KEY = ...
URL = ...
HEADERS = {
'Content-type': 'application/json',
'X-OnePass-API-Key': API_KEY,
'X-OnePass-ClientKey': CLIENT_KEY,
}
f = open('data.json', 'r')
# returns JSON object as
# an array
data = json.load(f)
# Iterating through the json
for d in data:
# Send HTTP request
response = requests.post(URL, headers=headers, json=d)
# Do whatever
...
f.close()
I'm trying to make confirmation slack button while running slash command. e.g. I run slash-command (/test) it sends the POST request to my python app which sends back 2 buttons (Confirm, Cancel). User presses one of the buttons slack triggers an action and sends another POST request to my app. All is working fine before this step - I cannot handle the data from 2nd POST request correctly.
In the Slack documentation I found this:
When an action is invoked, a request will be sent to the app's Request URL as configured above; the request body will contain a payload parameter that your app should parse for JSON.
When I do
data=json.loads(request.form["payload"])
return jsonify(data)
I get
{
"action_ts": "XXXX",
"actions": [
{
"name": "confirm",
"type": "button",
"value": "confirm"
}
],
"attachment_id": "X",
"callback_id": "XXXX",
"channel": {
"id": "XXXX",
"name": "XXXX"
},
"is_app_unfurl": false,
"message_ts": "XXXX",
"response_url": "XXXX",
"team": {
"domain": "XXXX",
"id": "XXXX"
},
"token": "XXXX",
"trigger_id": "XXXX",
"type": "interactive_message",
"user": {
"id": "XXXX",
"name": "XXXX"
}
}
After when I call
data=json.loads(request.form["payload"])
action=data["actions"]
return jsonify(action)
I get
[
{
"name": "confirm",
"type": "button",
"value": "confirm"
}
]
Now when I'm trying to get value of "name" with action["name"] I receive the error
TypeError: list indices must be integers or slices, not str
I tried json.dumps(action) and json.dumps(action["name"]) neither of them worked.
How to read that values? I need to check value of name and then do the rest with it.
[
{
"name": "confirm",
"type": "button",
"value": "confirm"
}
]
is a list containing one element - the dictionary. Access the name like data["actions"][0]["name"]
So i have build a REST Client that returns JSON response. However, i have an issue, where the JSON output is not exactly what i need:
Current Response:
{
"output": {
"status": "Device 'Test' does not exist",
"result": "null",
"response": {
"output": "success",
"result": 204
}
}
}
This output has an outermost enclosing "output" key, but i don't want that to be present. So basically i want my response to look like below:
{
"status": "Device 'Test' does not exist",
"result": "null",
"response": {
"output": "success",
"result": 204
}
}
I did try converting the JSON to Dict and then remove it, but no luck? any suggestions how to achieve this?
Thank you
if your response is already a dictionary or a json object then you can do following
value_required = response["output"]
if it is in text format (which I think it is) then you just need to do the following
import json
value_required = json.loads(response)["output"]
You should be able to do:
response = json.loads(response)['output']
I'm trying to write a python script that will read in a JSON file with the aim to show how many screens are available and be able to pull the value of the different json fields
JSON
{
"screen": [
{
"id": "1",
"user": "user1#example.com",
"password": "letmein",
"code": "123456"
},
{
"id": "2",
"user": "user2#example.com",
"password": "letmein",
"code": "123455"
},
{
"id": "3",
"user": "user3#example.com",
"password": "letmein",
"code": "223456"
}
]
}
Python
import json
from pprint import pprint
with open('screen.json') as data_file:
data = json.load(data_file)
#json_file.close()
pprint(data)
data["screen"][0]["id"]
As you can see from python script I can successfully print out the json file is pprint but when I try just find print out individual values I'm getting stuck
Am I doing something wrong here?
I want to be able to use all the values in json files as variables later on in python script to be able to be used with selenium to open a web page using this values?
I tested your example code and it works fine. It looks like you just forgot to actually print the value in the final line. That is:
data["screen"][0]["id"]
should be
pprint(data["screen"][0]["id"])
which prints u'1' when I try it.
I need to read this JSON URL: http://www.jsoneditoronline.org/?url=https://api.twitch.tv/kraken/streams/hazretiyasuo
My code:
geourl = "https://api.twitch.tv/kraken/streams/hazretiyasuo"
response = urllib.request.urlopen(geourl)
content = response.read()
data = json.loads(content.decode("utf8"))
for row in data['stream']
print data['game']
I can read 'stream' but i cant read 'game', game is inside of stream.
When I run the code in the question and then print out the json that gets returned, I get the following:
{
"_links": {
"channel": "https://api.twitch.tv/kraken/channels/hazretiyasuo",
"self": "https://api.twitch.tv/kraken/streams/hazretiyasuo"
},
"stream": null
}
The reason you can't get data['game'] is because the json you get back does not contain that information.