I am baffled and do not know how to solve this error. I'm trying to grab every name inside a JSON response list.
My code looks like this.
def extract_strucutres_ids(expected_structures):
response = requests.get(JIRA_REST + "/structures", verify=False)
response = response.json()
for structure in response['structures']:
print structure['name']
The Json reponse looks like this.
{
"structures": [{
"id": 165,
"name": "6.2 External Notifications Refactor",
"description": ""
}, {
"id": 364,
"name": "6.4 Day/Night Mode and Idle Scene Mode",
"description": "",
"readOnly": true
}, {
"id": 140,
"name": "ACC 5 Regression",
"description": ""
}
]
}
I keep getting List indicies must be integers, not str.
Python version 2.7.10
try this -
import json
def extract_strucutres_ids(expected_structures):
response = requests.get(JIRA_REST + "/structures", verify=False)
if response.status_code==200:
response_json = json.loads(response.text)
for structure in response_json['structures']:
print structure['name']
else:
print("Response is {}".format(response.status_code))
Let me know,if it worked!
Use json.loads()
response = requests.get(..)
response = json.loads(response.text) # response.text is a string
for structure in response['structures']:
# Do something
Related
I want to use the Microsoft Graph API to send messages with attachments to chats or channels.
https://learn.microsoft.com/en-us/graph/api/chatmessage-post?view=graph-rest-1.0&tabs=http#example-4-send-a-message-with-file-attachment-in-it
I can send normal messages already just fine like this:
def post_message(chat_id: str, subject: str = "", content_type: str = "text", content: str = "") -> None:
url = f"https://graph.microsoft.com/v1.0/chats/{chat_id}/messages"
json = {
"subject": subject,
"body": {
"contentType": content_type,
"content": content
}
}
res = requests.post(url, headers=header, json=json)
I try to copy the body from the example in the link above, substitute for my values and swap json variable for this one:
attachment_id = '7QW90B10D7-B5AK-420A-AC78-1156324A54F2' # not real, only to show how it looks like
json = {
"body": {
"contentType": 'html',
"content": f'i dunno what i\'m doing. <attachment id="{attachment_id}"></attachment>'
},
'attachments': [
{
'id': attachment_id,
'contentType': 'reference',
'contentUrl': 'https://foo.sharepoint.com/sites/bar/User%20documentation/Databricks/Databricks%20guide.pptx',
'name': 'Databricks guide.pptx'
}
]
}
I get requests.exceptions.HTTPError: 400 Client Error: Bad Request for url
What's wrong with the code? How to get attachment id from a file correctly because I am not sure I got the right value?
I was able to get it working with your code, (using both formats <attachment id=\"\"> and <attachment id="">), so it seems the error is probably with your attachment_id.
I retrieved the driveItem ID by following this answer, where the driveItem ID is the GUID value in the eTag property in the response.
You could get the file by the path:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/{item-path}
For example:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/test.docx
If the file is in a folder, it would be like this:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/folder1/test.docx
Sample request after obtaining the ID
access_token = ""
attachment_name = "file.txt"
attachment_path = "https://domain.sharepoint.com/Shared%20Documents"
attachment_id = "12345678-1234-1234-1234-123456789123"
attachment_url = f"{attachment_path}/{attachment_name}"
chat_id = ""
req_url = f"https://graph.microsoft.com/v1.0/chats/{chat_id}/messages"
req_headers = {
"Authorization": "Bearer " + access_token,
"Content-Type": "application/json"
}
json = {
"body": {
"contentType": "html",
"content": f"Test message <attachment id=\"{attachment_id}\"></attachment>"
},
"attachments": [
{
"id": attachment_id,
"contentType": "reference",
"contentUrl": attachment_url,
"name": attachment_name
}
]
}
result = requests.post(url = req_url, headers = req_headers, json = json)
resp = {
"Name": "test",
"os": "windows",
"Agent": {
"id": "2",
"status": [
{
"code": "123",
"level": "Info",
"displayStatus": "Ready",
"message": "running",
"time": "2022-01-18T09:51:08+00:00"
}
]
}
I am trying to get the time value from the JSON.
I tried the below code but faced error with dict
resp1 = json.loads(resp)
resp2 = resp1.values()
creation_time = resp2.get("Agent").get("status")
val= creation_time["time"]
print(val) ## Thrwoing error as dict_values has no 'get'
Any suggestion on python how to take this time values
Few problems I noticed
You are trying to load a Dict type using the json's loads function which is supposed to get a string in json format (ex: '{ "name":"John", "age":30, "city":"New York"}')
You tried to access resp2 before declaration (I guessed you meant "resp1?")
You're using resp3 without declaration.
You are missing }
You don't need the .value() function because it will return a list.
Also creation time is a list with one object, so you need to access it too.
Considering all this, you can change it as follows:
import json
resp = '{ "Name": "test", "os": "windows","Agent": {"id": "2","status": [{"code": "123","level": "Info","displayStatus": "Ready","message": "running","time": "2022-01-18T09:51:08+00:00"}]}}'
resp1 = json.loads(resp)
creation_time = resp1.get("Agent").get("status")
val= creation_time[0]["time"]
print(val)
You just need to access the dicts using [] like so:
resp = {"Name": "test", "os": "windows", "Agent": {"id": "2","status": [{"code": "123","level": "Info","displayStatus": "Ready","message": "running","time": "2022-01-18T09:51:08+00:00"}]}}
creation_time = resp["Agent"]["status"]
val= creation_time[0]["time"]
print(val)
Output:
2022-01-18T09:51:08+00:00
I have the following code
import requests
import json
import sys
credentials_User=sys.argv[1]
credentials_Password=sys.argv[2]
email=sys.argv[3]
def auth_api(login_User,login_Password,):
gooddata_user=login_User
gooddata_password=login_Password
body = json.dumps({
"postUserLogin":{
"login": gooddata_user,
"password": gooddata_password,
"remember":1,
"verify_level":0
}
})
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
url="https://reports.domain.com/gdc/account/login"
response = requests.request(
"POST",
url,
headers=headers,
data=body
)
sst=response.headers.get('Set-Cookie')
return sst
def query_api(cookie,email):
url="https://reports.domain.com/gdc/account/domains/domain/users?login="+email
body={}
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cookie': cookie
}
response = requests.request(
"GET",
url,
headers=headers,
data=body
)
jsonContent=[]
jsonContent.append({response.text})
accountSettings=jsonContent[0]
print(accountSettings)
cookie=auth_api(credentials_User,credentials_Password)
profilehash=query_api(cookie,email)
The code itself works and sends a request to the Gooddata API.
The query_api() function returns JSON similar to below
{
"accountSettings": {
"items": [
{
"accountSetting": {
"login": "user#example.com",
"email": "user#example.com",
"firstName": "First Name",
"lastName": "Last Name",
"companyName": "Company Name",
"position": "Data Analyst",
"created": "2020-01-08 15:44:23",
"updated": "2020-01-08 15:44:23",
"timezone": null,
"country": "United States",
"phoneNumber": "(425) 555-1111",
"old_password": "secret$123",
"password": "secret$234",
"verifyPassword": "secret$234",
"authenticationModes": [
"SSO"
],
"ssoProvider": "sso-domain.com",
"language": "en-US",
"ipWhitelist": [
"127.0.0.1"
],
"links": {
"projects": "/gdc/account/profile/{profile_id}/projects",
"self": "/gdc/account/profile/{profile_id}",
"domain": "/gdc/domains/default",
"auditEvents": "/gdc/account/profile/{profile_id}/auditEvents"
},
"effectiveIpWhitelist": "[ 127.0.0.1 ]"
}
}
],
"paging": {
"offset": 20,
"count": 100,
"next": "/gdc/uri?offset=100"
}
}
}
The issue I am having is reading specific keys from this JSON Dict, I can use accountSettings=jsonContent[0] but that just returns the same JSON.
What I want to do is read the value of the project key within links
How would I do this with a dict?
Thanks
Based on your description, uyou have your value inside a list, (not a set. Foergt about set: sets are not used with JSON). Inside your list, you either your content as a single string, which then you'd have to parse with json.loads, or it is simply a well behaved nested data structure already extracted from JSON, but which is inside a single element list. This seems the most likely.
So, you should be able to do:
accountlink = jsonContent[0]["items"][0]["accountSetting"]["login"]
otherwise, if it is encoded as a a json string, you have to parse it first:
import json
accountlink = json.loads(jsonContent[0])["items"][0]["accountSetting"]["login"]
Now, given your question, I'd say your are on a begginer level as a programmer, or a casual user, just using Python to automatize something either way, I'd recommend you do try some exercising before proceeding: it will save you time (a lot of time). I am not trying to bully or mock anything here: this is the best advice I can offer you. Seek for tutorials that play around on the interactive mode, rather than trying entire programs at once that you'd just copy and paste.
Using the below code fixed the issue
jsonContent=json.loads(response.text)
print(type(jsonContent))
test=jsonContent["accountSettings"]["items"][0]
test2=test["accountSetting"]["links"]["self"]
print(test)
print(test2)
I believe this works because for some reason I didn't notice I was using .append for my jsonContent. This resulted in the data type being something other than it should have been.
Thanks to everyone who tried helping me.
So I am using the urban dictionary api, and the code works perfectly as I would like: I'm going to use chicken as my term.
import json
import requests
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"chicken"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': "KEY"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data = response.text
json_object = json.loads(json_data)
print(json.dumps(json_object, indent = 4))
If I run this, I get the following which is the correct output, but I want to only print out the definition.
{
"list": [
{
"definition": "A [kilogram] of [cocain]. Dealers started calling kilos \"[birds]\" which then evolved into \"chicken.\"",
"permalink": "http://chicken.urbanup.com/1180537",
"thumbs_up": 2947,
"sound_urls": [
"http://api.twilio.com/2008-08-01/Accounts/ACd09691b82112e4b26fce156d7c01d0ed/Recordings/RE18c37ff43a6fc6dce8d9d533e7e4042b"
],
"author": "DEKE",
"word": "chicken",
"defid": 1180537,
"current_vote": "",
"written_on": "2005-04-11T11:41:04.000Z",
"example": "Person 1) [How much] you [got left]?\r\n\r\nPerson 2) A [quarter] chicken.",
"thumbs_down": 941
},
{
"definition": "To lack courage and [bravery]. [Unskilled], stupid, afraid, loser, [coward]",
"permalink": "http://chicken.urbanup.com/7399878",
"thumbs_up": 180,
"sound_urls": [
"http://api.twilio.com/2008-08-01/Accounts/ACd09691b82112e4b26fce156d7c01d0ed/Recordings/RE18c37ff43a6fc6dce8d9d533e7e4042b"
],
"author": "Freak Out Guy",
"word": "chicken",
"defid": 7399878,
"current_vote": "",
"written_on": "2013-12-10T16:49:06.660Z",
"example": "He was so afraid she [thought] he was [a chicken].",
"thumbs_down": 49
}
]
}
I've seen that you can do print(json_object['list'][0]['definition']), but it only prints out the first definition. How can I print out all the instances of definition like:
Definition 1: A [kilogram] of [cocain]. Dealers started calling kilos \"[birds]\" which then evolved into \"chicken.\"
Definition 2: To lack courage and [bravery]. [Unskilled], stupid, afraid, loser, [coward]
for idx, entry in enumerate(json_object['list'], 1):
print(f'Definition {idx}: {entry["definition"]}')
output
Definition 1: A [kilogram] of [cocain]. Dealers started calling kilos "[birds]" which then evolved into "chicken."
Definition 2: To lack courage and [bravery]. [Unskilled], stupid, afraid, loser, [coward]
You dont need to use the dump, u can use the json_object instead. Like this:
import json
import requests
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"chicken"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': "KEY"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data = response.text
json_object = json.loads(json_data)
#json_object = json.dumps(json_object, indent = 4)
print(json_object["list"][0]["definition"]) # you can use the for statement to get all the definitions
(Edit) All the definitions example:
import json
import requests
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"chicken"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': "KEY"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data = response.text
json_object = json.loads(json_data)
#json_object = json.dumps(json_object, indent = 4)
for i in json_object["list"]:
print(i["definition"])
I am trying to extract data from an API with python.
With this code, I am trying to print the content of dictionaries within a list.
response = requests.get(url, params=payload)
data = response.json()
log = json.dumps(data['result'], indent = 1)
print log
So far so good, it prints:
[
{
"line": "something#gmail.com:birthdaydate"
},
{
"line": "something#gmail.com:birthdaydate"
},
{
"line": "something#gmail.com:birthdaydate"
},
]
Is there a way for the output to look like below?
"something#gmail.com:birthdaydate"
"something#gmail.com:birthdaydate"
"something#gmail.com:birthdaydate"
Try this one:
response = requests.get(url, params=payload)
data = response.json()
log = data['result']
for l in log:
print(l["line"])