extract certain values from a JSON File (python) - python

Im getting a response from a request to my power plug that looks like this:
{"emeter":{"get_realtime":{"voltage_mv":235176,"current_ma":12,"power_mw":0,"total_wh":4525,"err_code":0}}}
Which I saved to the variable response
Now I want it to just give me the value of "current_ma" when I am sending the request.
How can I achieve this?
I tried something like response.current_ma, but that just gives me errors.

Like this:
response["emeter"]["get_realtime"]["current_ma"]
JSON is like a tree structure, where you need to reference the levels in the tree to where the data you are fetching is located.
I believe its good practice to wrap this in a try, in case the value is not present. Like this:
try:
my_var = response["emeter"]["get_realtime"]["current_ma"]
except KeyError as ex:
# do something useful if exception is thrown

You can use below code:
current_ma = response["emeter"]["get_realtime"]["current_ma"]
print("Antwort: {}".format(response["emeter"]["get_realtime"]["current_ma"]))

Related

TypeError: string indices must be integers when making rest api request

When I try to parse a rest api data,
it raises TypeError.
This is my code:
def get_contracts():
response_object = requests.get(
"https://testnet-api.phemex.com/md/orderbook?symbol=BTCUSD"
)
print(response_object.status_code)
for contract in response_object.json()["result"]["book"]:
print(contract["asks"])
get_contracts()
Any tip or solution will be very welcomed. Thanks in advance.
Edit/Update:
For some reason I am not able to select a specific key in the format above, its only possible if I do it like this:
data = response_object.json()['result']['book']['asks']
print(data)
I will try to work my code around that. Thanks for everyone who helped.
This code review may help you:
import requests
url = "https://testnet-api.phemex.com/md/orderbook?symbol=BTCUSD"
response_object = requests.get(url)
data = response_object.json()
# Printing your data helps to inspect the structure
# print(data)
# This is the list you are looking for:
asks = data['result']['book']['asks']
for ask in asks:
print(ask)
You need to iterate through asks, not book.
You have a nested dictionary where asks is a nested list.
If you simply click on the link you get getting, or print out your response_object.json() you would see the structure.
for foo in response_object.json()['result']['book']['asks']:
print(foo)
Although generally it's better to assign your response_object to a variable.
data = response_object.json()
for foo in data['result']['book']['asks']:
print(foo)
It looks like you are trying to access something that is not there, hence the KeyError.
I would debug, a simple print, the JSON object you are getting as answer and make sure that the keys you are trying to access are there.

transform JSON file to be usable

Long story short, i get the query from spotify api which is JSON that has data about newest albums. How do i get the specific info from that like let's say every band name or every album title. I've tried a lot of ways to get that info that i found on the internet and nothing seems to work for me and after couple of hours im kinda frustrated
JSON data is on jsfiddle
here is the request
endpoint = "https://api.spotify.com/v1/browse/new-releases"
lookup_url = f"{endpoint}"
r = requests.get(lookup_url, headers=headers)
print(r.json())
you can find the
When you make this request like the comments have mentioned you get a dictionary which you can then access the keys and values. For example if you want to get the album_type you could do the following:
print(data["albums"]["items"][0]["album_type"])
Since items contains a list you would need to get the first values 0 and then access the album_type.
Output:
single
Here is a link to the code I used with your json.
I suggest you look into how to deal with json data in python, this is a good place to start.
I copied the data from the jsfiddle link.
Now try the following code:
import ast
pyobj=ast.literal_eval(str_cop_from_src)
later you can try with keys
pyobj["albums"]["items"][0]["album_type"]
pyobj will be a python dictionary will all data.

Is there a python equivalent to the Unix '$?' command?

I am using fastjsonschema for validating json records against its schema.
Some thing like this:
import fastjsonschema
validate = fastjsonschema.compile({'type': 'string'})
validate('hello')
If the json is valid, it returns the json string else return the error string. I just want to check if the json is valid or not. For this I can do a workaround of comparing output of the validate method and the json input.
But I want something cleaner. May be something like '$?' in unix or something better.
Could you suggest me?
From the documentation, there seem to be two different exceptions thrown in case of error:
JsonSchemaDefinitionException, when the definition is bad
JsonSchemaException, when the data is not matching the definition
In Python, you can simply wrap that with a try ... except block like this:
try:
validate = fastjsonschema.compile({'type': 'string'})
validate(1)
except (fastjsonschema.JsonSchemaException, fastjsonschema.JsonSchemaDefinitionException):
print("Uh oh ...")

Getting http status code

Is there any way to get http status in non-numeric way. Like if I use http module I get http.HTTPStatus.ok which is numeric form of 200. However, I would like to get it as http.HTTPStatus.ok only in alphbetic way for comparision.
I am using a python code which executes an url and get the result back and result.response_code is http.HTTPStatus.ok.
Based on the documentation:
>>> import http
>>> http.HTTPStatus.OK.phrase
'OK'
Based on what you've written you should therefore be able to do something like result.response_code.phrase. If instead you get a number back you can reverse the lookup like this:
>>> http.HTTPStatus(200).phrase
'OK'

Python 2.7 replace all instances of NULL / NONE in complex JSON object

I have the following code..
.... rest api call >> response
rsp = response.json()
print json2html.convert(rsp)
which results in the following
error: Can't convert NULL!
I therefore started looking into schemes to replace all None / Null's in my JSON response, but I'm having an issue since the JSON returned from the api is complex and nested many levels and I don't know where the NULL will actually appear.
From what I can tell I need to iterate over the dictionary objects recursively and check for any values that are NONE and actually rebuild the object with the values replaced, but I don't really know where to start since dictionary objects are immutable..
If you look at json2html's source it seems like you have a different problem - and the error message is not helping.
Try to use it like this:
print json2html.convert(json=rsp)
btw. because I've already contributed to that project a bit I've opened up the following PR due to this question: https://github.com/softvar/json2html/pull/20

Categories