Parsing JSON string/object in Python - python

I've recently started working with JSON in python. Now I'm passing a JSON string to Python(Django) through a post request. Now I want to parse/iterate of that data. But I can't find a elegant way to parse this data, which somehow I'm pretty sure exists.
data = request.POST['postformdata']
print data
{"c1r1":"{\"Choice\":\"i1\"}","c2r1":"{\"Bool\":\"i2\"}","c1r2":"{\"Chars\":\"i3\"}"}
jdata = json.loads(data)
print jdata
{u'c1r2': u'{"Chars":"i3"}', u'c1r1': u'{"Choice":"i1"}', u'c2r1': u'{"Bool":"i2"}'}
This is what was expected. But now when I want to get the values, I start running into problems. I have to do something like
mydecoder = json.JSONDecoder()
for part in mydecoder.decode(data):
print part
# c1r2 c1r1 c2r1 ,//Was expecting values as well
I was hoping to get the value + key, instead of just the key. Now, I have to use the keys to get values using something like
print jdata[key]
How do I iterate over this data in a simpler fashion, so that I can iterate over key, values?

To iterate key and value, you can write
for key, value in jdata.iteritems():
print key, value
You can read the document here: dict.iteritems

Just for others to help. In Python3 dict.iteritems() has been renamed to dict.iter()

Related

Extract a dictionnary value in Python

I have an API call result in Python which is returning the following:
b'[{"type":"deposit","currency":"bch","amount":"0.00000001","available":"0.00000001"}]'
I tried to extract the value 0.00000001 but without any success.
I know how to extract values from lists and dictionaries in Python,but as there is the b' value before the results I am not figuring out how to get it.
Any ideas?
I think what you have here is actually a bytes string, rather than a Python dictionary. Try this to convert it to a dictionary (actually a list containing a dictionary given the square brackets):
import json
data = json.loads(b'[{"type":"deposit","currency":"bch","amount":"0.00000001","available":"0.00000001"}]')
value = data[0]['amount']
The API is probably returning json data, you should parse it this way:
import json
data = json.loads(json_data)
print data[0]['amount']
json_data is what the API returns

Get fields from a specific Jira issue

I'm trying to get all the fields and values from a specific issue my code:
authenticated_jira = JIRA(options={'server': self.jira_server}, basic_auth=(self.jira_username, self.jira_password))
issue = authenticated_jira.issue(self.id)
print issue.fields()
Instead of returning the list of fields it returns:
<jira.resources.PropertyHolder object at 0x108431390>
authenticated_jira = JIRA(options={'server': self.jira_server}, basic_auth=(self.jira_username, self.jira_password))
issue = authenticated_jira.issue(self.id)
for field_name in issue.raw['fields']:
print "Field:", field_name, "Value:", issue.raw['fields'][field_name]
Depends on field type, sometimes you get dictionary as a value and then you have to find the actual value you want.
Found using:
print self.issue_object.raw
which returns the raw json dictionary which can be iterate and manipulate.
You can use issue.raw['fields']['desired_field'], but this way is kind of indirectly accessing the field values, because what you get in return is not consistent. You get lists of strings, then just strings themselves, and then straight up values that don't have a key for you to access them with, so you'll have to iterate, count the location, and then parse to get value which is unreliable.
Best way is to use issue.fields.customfield_# This way you don't have to do any parsing through the .raw fields
Almost everything has a customfield associated with it. You can pull just issues from REST API to find customfield #'s, or some of the fields that you get from using .raw will have a customfield id that should look like "customfield_11111" and that's what you'll use.
Using Answer from #kobi-k but dumping in better format, I used following code:
with open("fields.txt", "w") as f:
json.dump(issue.raw, f, indent=4)
It dumped all the fields in a file with name "fields.txt"

Parse JSON in python to a dictionary

A bit lost after much research. My code below parses the JSON to a dictionary I have thought using json load
response = json.load(MSW) # -->Will take a JSON String & Turn it into a python dict
Using the iteration below I return a series like this which is fine
{u'swell': {u'components': {u'primary': {u'direction': 222.5}}}}
{u'swell': {u'components': {u'primary': {u'direction': 221.94}}}}
ourResult = response
for rs in ourResult:
print rs
But how oh how do I access the 222.5 value. The above appears to just be one long string eg response[1] and not a dictionary structure at all.
In short all I need is the numerical value (which I assume is a part of that sting) so I can test conditions in the rest of my code. Is is a dictionary? With thanks as new and lost
You have to use python syntax as follows:
>>> print response['swell']['components']['primary']['direction']
222.5
Just access the nested dictionaries, unwrapping each layer with an additional key:
for rs in ourResult:
print rs['components']['primary']['direction']

ConfigParser Get Key on given Value

Using ConfigParser I can read value of key easily as shown in the example below-
#config.cfg
[NODE]
192.168.31.22 = node22
192.168.31.23 = node23
192.168.31.26 = node26
#PYTHON CODE
config = ConfigParser.RawConfigParser()
config.readfp(open("config.cfg"))
print config.get("NODE", "192.168.31.22")
>>>node22
Sometime it is required that I read "key" based on given value.
Is there any built-in function to get KEY based on the given VALUE or any workaround for this ?
print config.FUNCTIONXYZ("NODE", "node22")
>>>192.168.31.22
Thank you.
No, there is no direct way. Internally, ConfigParser reads the configuration file into a nested dictionary, and in each sections keys are mapped to values, not the other way around. Frankly, I'm not sure why you want this, but I suspect it's not a common request :)
Implementing your own is very easy, however:
# items in section 'NODE': key, value pairs
for key, value in config.items('NODE'):
if value == WHAT_I_NEED:
print key
If you need many such lookups on a large configuration, consider placing items into a dict first.

How to decode JSON with Python [duplicate]

This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed 3 years ago.
I'm getting my JSON from reddit.com, essentially something like this. I have done quite a bit of reading, but I don't really understand how I can grab the information I want from this JSON (I want a list of the story links). I understand that I can "decode" the JSON into a dictionary, but do I need to recur throughout the JSON to get what I need?
Thanks in advance.
If you're using Python 2.6 or later, use the built-in json library. Otherwise, use simplejson which has exactly the same interface.
You can do this adaptively without having to check the Python version yourself, using code such as the following:
try:
import json
except ImportError:
import simplejson as json
Then, use json.loads() or whatever as appropriate.
import urllib2
import json
u = urllib2.urlopen('http://www.reddit.com/.json')
print json.load(u)
u.close()
There are two ways you can "decode" json with Python, after you've parsed it into dicts and lists with the json library.
First, accessing it by indexes, like this:
url_list = [t['entries'][0]['url'] for t in data['windows'][0]['tabs']]
Or, you can iterate over its tree structure. The example function below isn't general purpose, it just illustrates that you need to consider JSON's three different kinds of "nodes" differently when parsing the tree. A key's "value" might be data, a list of child nodes with no keys, or a dict that's basically a new JSON object. You can't just run through checking every node for its name, data, and children like you would with a regular tree.
def depthFirstSearch(self, jsonobj, target, parentKey=None):
if isinstance(jsonobj, dict):
for key, value in jsonobj.items():
if isinstance(value, (dict, list)):
self.depthFirstSearch(value, target, key)
else: # "data" node
if key == target and parentKey not in self.parentsToExclude:
self.results.append(value)
self.parents[parentKey] += 1
if isinstance(jsonobj, list):
for value in jsonobj:
#lists don't have keys, pass along key from last dict
self.depthFirstSearch(value, target, parentKey)

Categories