How to parse this json using python - python

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)

Related

Is it possible to increment a value with F in a json field in django?

Is it possible to increment a value with F in a json field in django?
I have an object that contains a json field and I have some keys in it.
Is it possible to increment the key value inside a json used F?
Thank you for all.
credits = Company.objects.filter().first()
credits.meta_data = F('meta_data')['credits'] + 1
credits.save()
Not sure what F is, but given you meta_data is a valid JSON object, you can manipulate it with json library, for instance:
a = json.loads("{\"a\":1}")
#or a = json.loads(credits.meta_data)
print(a)
a["a"] = a["a"]+1
print(a)
{'a': 1}
{'a': 2}
You want to be careful (handle exceptions and ensure you save valid json content into this field), because even when you are using postgresql-specific json field, it does not guarantee that you are getting a properly formatted json objects from it.

Modifying json string going into list or dictionary?

I am new to Python and working on revising some existing code.
There is a JSON string coming into a Python function that looks like this:
{"criteria": {"modelName":"='ALL'", "modelName": "='NEW'","fields":"*"}}
Right now it appears a dictionary is being used to create a string:
crit=data['criteria']
for crit_key in crit
crit_val = crit[crit_key]
sql+ = sql+= ' and ' + crit_key + crit_val
When the sql string is printed, only the last 'modelName' appears. It seems like a dictionary is being used as modelName is a key so the second modelName overwrites the first? I want the "sql" string in the end to contain both modelNames.
edited because of OP comments
Well, if you can't update your JSON and have to deal with.
You can make something like:
data = '{"criteria": {"modelName":"=\'ALL\'", "modelName": "=\'NEW\'","fields":"*"}}'
import json
def dict_raise_on_duplicates(ordered_pairs):
d = {}
duplicated = []
for k, v in ordered_pairs:
if k in d:
if k not in duplicated:
duplicated.append(k)
d[k] = [d[k]] + [v]
else:
d[k].append(v)
else:
d[k] = v
return d
print json.loads(data, object_pairs_hook=dict_raise_on_duplicates)
In this example, data is the JSON string with duplicated keys.
According to json.loads allows duplicate keys in a dictionary, overwriting the first value I just force json.load to handle duplicate keys.
If a duplicated key is spotted, it will create a new list containing current key data and add new value.
After, it will only append news values in created list.
Output:
{u'criteria': {u'fields': u'*', u'modelName': [u"='ALL'", u"='NEW'"]}}
You will have to update your code anyway, but you now can handle it.

Python:Get value of a dictionary present in aTuple

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

Python 3. Extract data from json

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()

Parse json data

My data.json is
{"a":[{"b":{"c":{ "foo1":1, "foo2":2, "foo3":3, "foo4":4}}}],"d":[{"e":{"bar1":1, "bar2":2, "bar3":3, "bar4":4}}]}
I am able to list both key/pair values. My code is:
#! /usr/bin/python
import json
from pprint import pprint
with open('data2.json') as data_file:
data = json.load(data_file)
pprint(data["d"][0]["e"])
Which gives me:
{u'bar1': 1, u'bar2': 2, u'bar3': 3, u'bar4': 4}
But I want to display only the keys without any quotes and u like this:
bar1, bar2, bar3, bar4
Can anybody suggest anything? It need not be only in python, can be in shell script also.
The keys of this object are instances of the unicode string class. Given this, the default printing behavior of the dict instance for which they are the keys will print them as you show in your post.
This is because the dict implementation of representing its contents as a string (__repr__ and/or __str__) seeks to show you what objects reside in the dict, not what the string representation of those objects looks like. This is an important distinction, for example:
In [86]: print u'hi'
hi
In [87]: x = u'hi'
In [88]: x
Out[88]: u'hi'
In [89]: print x
hi
This should work for you, assuming that printing the keys together as a comma-separated unicode is fine:
print ", ".join(data["d"][0]["e"])
You can achieve this using the keys member function from dict too, but it's not strictly necessary.
print ', '.join((data["d"][0]["e"].keys()))
data["d"][0]["e"] returns a dict. In python2, You could use this to get the keys of that dict with something like this:
k = data["d"][0]["e"].keys()
print(", ".join(k))
In python3, wrap k in a list like this
k = list(data["d"][0]["e"].keys())
print(", ".join(k))
Even simpler, join will iterate over the keys of the dict.
print(", ".join(data["d"][0]["e"]))
Thanks to #thefourtheye for pointing this out.

Categories

Resources