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.
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 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)
Writing a bulk PUT to the CF Workers KV in Python and can’t figure out what’s wrong here. My JSON is valid as far as I can tell.
Here is the error I’m getting
Error
{ "result": null, "success": false, "errors": [ { "code": 10012, "message": "could not parse array of key/value objects from request body: 'could not unmarshal KVPair into intermediate struct: 'json: cannot unmarshal object into Go struct field kvPairJSON.value of type string''" } ], "messages": [] }
Payload
[{ “key”:“aals”, “value”:{ “sup”:{ “firo”:“aals”, “mean”:“aals”, “alpha”:[]}}}]
Code
response = requests.put(f"{CF_BASEURL}/bulk", headers=headers, data=json.dumps(payload))
Any ideas appreciated. I'm sure this is a SMH moment...
That's a useless error message, sorry about that. Workers KV values are plain bytes that may be deserialized in a Worker if needed (e.g. parsed as JSON). I think what you want to do there is just,
import json
payload = [{ "key": "aals", "value": json.dumps('{"sup": {"firo": "aals", "mean": "aals", "alpha": []}}')}]
So that your value is encoded as a string. And then in your Worker you can,
let jsonValue = KV_NAMESPACE.get("aals", "json");
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 have found some behaviour of Flask-restful caused I think by Werkzeug/0.9.4 that I do not understand. It seems that the use of Multidict is breaking my data when I try to POST valid JSON that contains a "=".
Here's my test JSON:
{
"alert": {
"#id": "90",
"action": "hoojimaflip",
"fruit": {
"#bowl": "bananas",
"#protocol": "tcp"
},
"url": "https://this-is-a-sample/paramer?id=90"
}
}
Here is the POST method.
def post(self):
f1=open("./log", 'w+')
data = request.json
if not data:
# I know this is not equivalent to the JSON above.
# Just troubleshooting by dumping it all out.
data = request.form
print >>f1, data
return ('', 201)
If I POST using cURL with application/json it's fine. I get the POSTed JSON correctly in request.data. I will need to render it back to JSON later, but no issue.
{
u'alert': {
u'#id': u'90'
u'action': u'hoojimaflip',
u'fruit': {
u'#bowl': u'bananas',
u'#protocol': u'tcp'
},
u'url': u'https://this-is-a-sample/paramer?id=90',
}
}
If I post via cURL with application/x-www-form-urlencoded, then I should be able to get the data in request.form. But, it seems that something is breaking my data.
ImmutableMultiDict([('
{ "alert": {
"#id": "90",
"action": "hoojimaflip",
"fruit": {
"#bowl": "bananas",
"#protocol": "tcp"
},
"url": "https://this-is-a-sample/paramer?id', u'90"
}
}'
)])
The "=" sign is being used as some kind of record separator and breaking the POSTed JSON.
Does anyone have any ideas? Am I missing something obvious?
Thanks!
If an external application is stubbornly POST-ing with an alternative mime-type, you can force Flask to treat the data as JSON anyway by using the request.get_json() method instead, setting the force argument to True:
data = request.get_json(force=True)
Don't try to treat a JSON payload as form data, that'll never work.