How to extract 41677?
My json:
{"41677":{"key":"ilya","premium":"true"}}
My code:
params={"id": "ilya", "fmt": "json"}
r=requests.get("somesite", params=params )
data=json.loads(r.text)
By using loads, your JSON string will be converted to a dictionary which maps keys to values.
Since you need the key 41677, you can simply call data.keys()[0] to retrieve the first key of your dictionary.
EDIT:
Also, if you have a list of that JSON structure, you can iterate over the keys and values using the items function, like so:
for key, value in data.items():
print key # 41677
print value # {"key":"ilya","premium":"true"}
By using Requests' built-in json attribute:
data = requests.get("somesite", params=params ).json().keys()[0]
assuming the json it returns is {"41677":{"key":"ilya","premium":"true"}}:
>>>print data
"41677"
import json
s = {"41677":{"key":"ilya","premium":"true"}}
d = json.dumps(s)
l = json.loads(d)
l.keys()
Related
Write a function named "get" that takes a JSON formatted string as a parameter in the format "{"attack": float, "decay": float, "sustain": float, "release": float}" and returns the value at the key "attack".
import json
def get(JSON):
load = json.loads(JSON)
dictionary = {}
attack = [f[0] for f in load]
attack1 = dictionary.update(attack)
for key, value in attack1.items():
if key == 'attack':
return value
My question is how do I take the specific value ('attack') in a JSON formatted string?
Once you've loaded it using json.loads(), you've converted it from a string to a dictionary. That means that the load variable you assign in load = json.loads(JSON) is already a dictionary, and you can access it using normal python dictionary syntax from there:
import json
def get(JSON):
load = json.loads(JSON)
return load["attack"]
So if your question is how to obtain the value of attack from JSON then do this:
load = json.loads(JSON)
load["attack"]
json.loads() makes the json into a python dictionary.
I currently have a Python Dictionary that looks something like this:
OrderedDict([('2017-07-24', 149.7619), ('2017-07-25', 150.4019), ('2017-07-26', 151.1109), ...
that I am converting to JSON like so:
one_yr = json.dumps(priceDict)
Currently I am adding values to the dictionary from an SQL query by looping through it like so:
for i in query:
date = i[0]
close = i[1]
priceDict[date] = close
The problem is that this returns a JSON object, that i then have to convert to a JSON array.
I am wondering if I can just convert my Python Dictionary to a JSON array directly? Thanks.
json.dumps(list(priceDict.items()))
But why do you have an OrderedDict in first place? If you pass the same list you passed to OrderedDict to json.dumps it will generate your array:
json.dumps([('2017-07-24', 149.7619), ('2017-07-25', 150.4019),....])
No need for OrderedDict in this case
If you want to convert a Python Dictionary to JSON using the json.dumps() method.
`
import json
from decimal import Decimal
d = {}
d["date"] = "2017-07-24"
d["quantity"] = "149.7619"
print json.dumps(d, ensure_ascii=False)
`
I removed the OrderedDict but kept all the other data, I think I understand the request. See if this works for you:
import json
my_dict = ([('2017-07-24', 149.7619), ('2017-07-25', 150.4019), ('2017-07-26', 151.1109)])
print(json.dumps(my_dict, indent=4, sort_keys=True))
I have just made a program to parse some data from an api. The api gives data back with a JSON format. When I try to parse it it gives me a key error
url = json.loads(r.text)["url"]
KeyError: 'url'
This is the part of the code
url = json.loads(r.text)["url"]
I am trying to get the data in the plain field. Here is the output from the API:
{"updates":[{"id":"a6aa-8bd","description":"Bug fixes and enhancemets","version":"8.1.30","type":"firmware","url":"https://con-man.company.com/api/v1/file-732e844b","updated":"2017-07-25"}]}
You cannot access url since it is inside update (list), therefore you need to Pass index and then key :
One liner:
>>> url = json.loads(r.text)['updates'][0]['url']
'https://con-man.company.com/api/v1/file-732e844b'
Explicit
>>> jobj = json.loads(r.text)
>>> url = jobj['updates'][0]['url']
'https://con-man.company.com/api/v1/file-732e844b'
try this,
url = json.loads(r.text)["updates"][0]["url"]
{
"updates": [
{
"id":"a6aa-8bd",
"description":"Bug fixes and enhancemets",
"version":"8.1.30",
"type":"firmware",
"url":"https://con-man.company.com/api/v1/file-732e844b",
"updated":"2017-07-25"
}
]
}
Try to visualize of your dict, it has only one key "update" in that key value it has another list and into that list, you has another dict
so if in your case
_dict = json.loads(r.text) # read file and load dict
_list = _dict['updates'] # read list inside dict
_dict_1 = _list[0] # read list first value and load dict
url = _dict_1['url'] # read 'url' key from dict
I used this and works now for me.
json_object = json.loads(response.content.decode("utf-8"))['list'][0]['localPercentDynamicObjectsUsed']
I have a tuple like: t= ({'count': 5L},)
Here i don't want to use for loop but want to get value as 5.Then how can i do it?
I tried with coverting to string then using JSON.
import json
s = str(t)
d = json.loads(s)
I got error:ValueError: No JSON object could be decoded
And winded up with no result.
I want to get the value of count as integer 5 & store in a variable.
Anyone having any idea?
No need to use Json since it is already your tuple is already a Python data structure.
If you know the index of the item in the tuple, and you know the keyname you can access it directly using:
t = ({'count': 5L},)
value = int(t[0]['count'])
I know its kind of trivial thing to ask...but i'm a new bee to python.
Here is a json string
reply = {u'f': [{u'v': u'0'}]}
How to parse out value 0 from it using python.
i tried like
count = reply['rows'][0]['v']
but it not working
count = reply['f'][0]['v'] should work I believe.
reply is a dictionary. As such, you need to use the dictionary keys to access the data. In this case, the key is 'f', not 'rows'.
If you had valid JSON, you could use the simplejson module:
from simplejson import loads, dumps
my_dict = loads(my_json_serialized_string)
and then you can access the python dict, e.g.,:
print my_dict.items()
print my_dict.keys()
print my_dict.values()
#lets assume 'rows' exists as a key, and the value is a list, and the first item of that list is a dict that contains the key 'v':
print my_dict['rows'][0]['v']
and you can even change the dict, and serialize it as a valid JSON string:
my_dict['my_key'] = 'my_value'
my_other_json_serialized_string = dumps(my_dict)