how to get Parameters from a json file with python - python

I am working in Python with a JSON file. When I print date it comes out like this :
print (date['slot'])
[{'slot': 1, 'type': {'url': 'https://pokeapi.co/api/v2/type/11/', 'name':
'water'}}]
But I just want to get 'water'. I have been using different methods and it did not work. Can someone please help me to get just 'water' from the code?

print (date['slot'][0]['type']['name'])
OR
print (date['slot'][0]['type']['name'] if date['slot'] else None)
OR More generic
for sd in date['slot']:
print (sd['type']['name'])

Related

Trying to Parse a JSON using Python but having issues

I usually use Powershell and have parsed JSONs from HTTP requests, successfully, before. I am now using Python and using the 'Requests' library. I have successfully got the JSON from the API. Here is the format it came through in (I removed some information and other fields).:
{'content': [
{
'ContactCompany': Star,
'ContactEmail': test#company.star,
'ContactPhoneNumber': 123-456-7894,
'assignedGroup': 'TR_Hospital',
'assignedGroupId': 'SGP000000132297',
'serviceClass': None, 'serviceReconId': None
}
]
}
I'm having trouble getting the values inside of the 'content.' With my Powershell experience in the past, I've tried:
tickets_json = requests.get(request_url, headers=api_header).json()
Tickets_Info = tickets_json.content
for tickets in tickets_info:
tickets.assignedGroup
How do I parse the JSON to get the information inside of 'Content' in Python?
tickets_json = requests.get(request_url, headers=api_header).json()
tickets_info = tickets_json['content']
for tickets in tickets_info:
print(tickets['assignedGroup'])

How to access specific parts of JSON for API call - Python

I want to access 'employmentName' and 'jobTile' values.
But I keep on getting this error - KeyError: 'jobTitle' and KeyError: 'employmentName'
Here is my code below, please note I am not sharing the api URL on this question but it is present and working in the code.
api_three_url = "https://xxxx"
json_data_three = requests.get(api_three_url, headers=my_headers).json()
#print(json_data_three) #this prints the whole json data (working!)
print("So you have previously worked in", json_data_three['employmentName'],"as a", json_data_three['jobTitle'])
This is what the JSON looks like in python dict:
{
'hasAddedValue': False,
'employments': [{
'id': 527,
'employmentName': 'Sallys hair',
'jobTitle': 'Stylists',
'jobStartDate': '2019-03',
'jobEndDate': '2020-04',
'jobType': 'PAID',
'status': True,
'isJobCurrent': False
}]
}
Please guide me to where I am going wrong.
Many thanks :)
The employmentName and jobType fields are not at the top level in your JSON, hence Python is giving you KeyError. They are actually in one of the objects inside employments.
So if you want to obtain those fields from the first object inside employments, it would be:
json_data_three['employments'][0]['employmentName']

Python pypi proxy-checker output?

So I installed this python tool: https://pypi.org/project/proxy-checker/
And I also installed PycURL
And my code is
checker = ProxyChecker()
checker.check_proxy('202.138.248.72:43037')
And its says that all is working, but where can I see the results like at the link?
Do I have to link anything?
You need to print the result:
from pprint import pprint
from proxy_checker import ProxyChecker
checker = ProxyChecker()
pprint(checker.check_proxy('202.138.248.72:43037'))
{'anonymity': 'Elite',
'country': 'Indonesia',
'country_code': 'ID',
'protocols': ['socks4'],
'timeout': 797}
.check_proxy() returns the result. You need to catch that and use in whatever way you want:
result = checker.check_proxy('202.138.248.72:43037')
For example, you can print the results:
print(results)
If you want just print and nothing else you can print directly:
print(checker.check_proxy('202.138.248.72:43037'))

Can't reach nested JSON in python 3.8

Working with a response from a Websockets subscription.
The response reads like this:
{'jsonrpc': '2.0', 'method': 'subscription', 'params': {'channel': 'book.BTC-PERPETUAL.none.1.100ms', 'data': {'timestamp': 1588975154127, 'instrument_name': 'BTC-PERPETUAL', 'change_id': 19078703948, 'bids': [[10019.5, 8530.0]], 'asks': [[10020.0, 506290.0]]}}}
And I'm trying to reach the first and only values inside "bids" and "asks" arrays via json.loads()
Code looks like this:
async def __async__get_ticks(self):
async with self.ws as echo:
await echo.send(json.dumps(self.request))
while True:
response = await echo.receive()
responseJson = json.loads(response)
print(responseJson["params"]["data"])
And error says:
print(responseJson["params"]["data"])
KeyError: 'params'
However I try, it doesn't want to catch any of the JSON after "jsonprc", for which it successfully returns 2.0. Anything beyond that always comes up with an error.
I tried using .get(), and it helps to go one level deeper, but still not more.
Any ideas on how to format this properly and reach the bids and asks ?
Thank you in advance.
I would suggest using the dict.get() method, but make sure that you set it to return an empty dictionary when querying dictionaries that are expected to have nested dicts.
By default (if you don't specify a second argument to dict.get()), it will return None. This explains why you were only able to go one level deep.
Here's an example:
empty_dict = {}
two_level_dict = {
"one": {
"level": "deeper!"
}
}
# This will return None and the second get call will not fail, because
# the first get returned an empty dict for the .get("level") call to succeed.
first_get = empty_dict.get("one", {}).get("level")
# This will return 'deeper!'
second_get = two_level_dict.get("one", {}).get("level")
print(first_get)
print(second_get)

How do I add a Key/Value in JSON with Python? [duplicate]

This question already has answers here:
How to update json file with python [duplicate]
(4 answers)
Closed 5 years ago.
This may sound like an average question, but I haven't found a good answer to what I am trying to do.
Take d.json:
{"SDA":{"Info":{"Description":"Anti Advertisment Bot, Blocks invites extensively.","Download Link":"http://sda.khionu.net/docs/, http://sda.khionu.net/docs/"}}, "Unit 02":{"Info":{"Description":"Server logging bot, c!serverlogs 'server name here if spaces' <# 1-9999>","Download Link":"https://discordapp.com/oauth2/authorize?client_id=222881716606468096&scope=bot&permissions=32768"}}}
I'm trying to add this to it, separated by commas:
{'Ctest': {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}}
I tried multiple ways to do it, but none works. Here's my current code
a = d[toolname] = {str(toolname):{"Info":{"Description": tooldesc, "Download Link": toollink}}}
f.write(str(a))
f.close()
return jsonify(a), 201
My whole goal is to write
{'Ctest': {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}}
to d.json like this
{"SDA":{"Info":{"Description":"Anti Advertisment Bot, Blocks invites extensively.","Download Link":"http://sda.khionu.net/docs/, http://sda.khionu.net/docs/"}}, "Unit 02":{"Info":{"Description":"Server logging bot, c!serverlogs 'server name here if spaces' <# 1-9999>","Download Link":"https://discordapp.com/oauth2/authorize?client_id=222881716606468096&scope=bot&permissions=32768"}}, {'Ctest': {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}}
Use json module for that, code below shall give you the clue:
import json
data = json.load('path_to_json_file')
data['key'] = 'value'
json.dump('path_to_json_file', data)
You can use this:
jsonObject['Ctest'] = {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}
Thanks to franklinsijo, I found an answer, and it is a duplicate, surprise surprise.
I reformatted the code to this:
a = d[toolname] = {toolname:{"Info":{"Description": tooldesc, "Download Link": toollink}}}
with open('data1.json', 'w') as f:
f.write(json.dumps(d))
f.close()
return jsonify(a), 201
Thanks for answering guys, I'll flag as a duplicate of his question.

Categories