Listing data inside a JSON object - python

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

Related

Print specific instances of json response

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

How to create a list from api reponse and remove duplicates

I want to make a list from api json response as shown for each ticket in jira and remove any duplicates
I can get the values for each ticket but not able to make it as list and remove duplicates from it to process
Here is the api json response for each ticket
response = {
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "1831845",
"self": "https://jira.com/login/rest/api/latest/issue/1845",
"key": "pc-1002",
"fields": {
"customfield_1925": {
"self": "https://jira.com/login/rest/api/2/customFieldOption/1056",
"value": "windows",
"id": "101056"
}
so i have script like this:
import requests, json
tick = """jira: pc-1002,pc-1003,pc-1005
env"""
ticks = tick.replace(' ','').split(':')[1].split('\n')[0].split(',')
print(ticks)
for i in ticks:
url = "https://jira.com/login/rest/api/latest/issue/" + str(i)
print(url)
response = requests.request("GET", url, verify=False)
response = json.loads(response.text)
resp = response['fields']['customfield_1925']['value']
print(resp)
so it prints all the values like below :
output:
windows1
windows2
windows1
I want the output values to be unique and as it may end up having duplicates.
I wanted output as below
['windows1', 'windows2']
Simply add each response to a list of responses, and use Python's convenient "in" operator to check if each response is already in the list. Something along the lines of:
allResponses = []
for i in ticks:
url = "https://jira.com/login/rest/api/latest/issue/" + str(i)
print(url)
response = requests.request("GET", url, verify=False)
response = json.loads(response.text)
resp = response['fields']['customfield_1925']['value']
if resp not in allResponses:
print(resp)
allResponses.append(resp)

Python currency calculation with API JSON

I'm new in this Python world, I'm trying to use an API to make basic currency calculations. I can get the output like:
{'USD': 1.13}
this but I want it just to be
1.13
The code:
import requests
inputCurrency = 'EUR'
outputCurrency = 'USD'
p = {"inpc":inputCurrency, "outc":outputCurrency}
url = 'https://somewebsite/api/data'
r = requests.get(url, params=p)
print(r.json())
The server returned a JSON object. The .json() method of your r response decodes it, and returns the decoded object, which is a Python dict.
You want the value corresponding to the 'USD' key.
Just do:
import requests
inputCurrency = 'EUR'
outputCurrency = 'USD'
p = {"inpc":inputCurrency, "outc":outputCurrency}
url = 'https://somewebsite/api/data'
response = requests.get(url, params=p)
json_data =response.json()
print(json_data['USD'])
If the structure of the data is more complicated, as in your comment:
json_data = { "status": 1, "data": [ { "time": "2015-08-30T07:56:28.000Z", "usd": 1.17 }, { "time": "2015-08-30T08:56:28.000Z", "usd": 1.27 }, { "time": "2015-08-30T09:56:28.000Z", "usd": 1.28 }]}
you could extract the relevant part:
data = json_data['data']
which is a list of dictionaries. You can then print the first one:
print(data[0]['usd'])
# 1.27
or print them all:
for day_value in data:
print(day_value['usd'])

List indicies must be integers. not str JSON reponse

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

Get all values from a JSON object and store in a flat array with Python

I am returning a JSON object from a requests call. I would like to get all the values from it and store them in a flat array.
My JSON object:
[
{
"link": "https://f.com/1"
},
{
"link": "https://f.com/2"
},
{
"link": "https://f.com/3"
}
]
I would like to store this as:
[https://f.com/things/1, https://f.com/things/2, https://f.com/things/3]
My code is as follows.. it is just printing each link out:
import requests
import json
def start_urls_data():
url = 'http://106309.n.com:3000/api/v1/product_urls?q%5Bcompany_in%5D%5B%5D=F'
headers = {'X-Api-Key': '1', 'Content-Type': 'application/json'}
r = requests.get(url, headers=headers)
start_urls_data = json.loads(r.content)
for i in start_urls_data:
print i['link']
You can use a simple list comprehension:
data = [
{
"link": "https://f.com/1"
},
{
"link": "https://f.com/2"
},
{
"link": "https://f.com/3"
}
]
print([x["link"] for x in data])
This code just loops through the list data and put the value of the key link from the dict element to a new list.

Categories