Extract python objects from a string - python

I have files with data looking like
{u'session_id': u'6a208c8cfada4048b26ea7811cbac20f'}
That is, key value pairs and arrays of objects with key value pairs which are of the form u'key' : u'value'
More specifically, the files I see look like what one gets after calling json.loads()on a JSON file.
I want to some how get the data present in these files as python objects or at least valid JSON format (some thing like reverse of json.loads()) so that I can do something like obj['session_id'] and get "6a208c8cfada4048b26ea7811cbac20f".
Thanks in advance

You can use literal_eval from the ast module, which is better than using eval directly:
>>> ast.literal_eval("{u'session_id': u'6a208c8cfada4048b26ea7811cbac20f'}")['session_id']
u'6a208c8cfada4048b26ea7811cbac20f'
>>> z = ast.literal_eval("{u'session_id': u'6a208c8cfada4048b26ea7811cbac20f'}")
>>> isinstance(z, dict)
True

Related

convert string representation of a dict inside json dict value to dict

Hello all and sorry if the title was worded poorly. I'm having a bit of trouble wrapping my head around how to solve this issue I have encountered. I would have liked to simply pass a dict as the value for this key in my json obj but sadly I have to pass it as a string. So, I have a json dict object that looks like this
data = {"test": "Fuzz", "options": "'{'size':'Regular','connection':'unconnected'}'"}. Obviously, I would prefer that the second dict value weren't a string representation of a dictionary but rather a dictionary. Is the best route here to just strip the second and second to last single quotes for the data[options] or is there a better alternative?
Sorry for any confusion. This is how the json object looks after I perform
json.dump(data, <filename>)
The value for options can be thought of as another variable say x and it's equivalent to '{'size':'Regular','connection':'unconnected'}'
I could do x[1:-1] but I'm not sure if that is the most pythonic way to do things here.
import ast
bad_string_dict = "'{'size':'Regular','connection':'unconnected'}'"
good_string_dict = bad_string_dict.strip("'")
good_dict = ast.literal_eval(good_string_dict)
print(good_dict)
You will have to strip quotation mark, no other way around
Given OP's comments I suggest the following:
Set the environment variable to a known data format (example: json/yaml/...), not a specific language (python)
Use the json module (or the format you've chosen) to load the data
The data should look like this:
raw_data = {"test": "Fuzz", "options": "{\"size\": \"Regular\", \"connection\": \"unconnected\"}"}
And the code should look like this:
raw_options = raw_data['options']
options = json.loads(raw_options)
data = {**raw_data, 'options': options}

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

How to get value using key in python multi dictionary

{
"card_quota": 0,
"custom_data": "{\"child_name\":\"홍설\",\"uid\":\"29\",\"lid\":\"56\",\"count\":\"1\",\"schedule\":\"2016-06-18(토)\"}",
"escrow": false
}
This is dictionary type of python. I konw to get value using a code like temp['card_quata']. But i want to know using key in ['custom_data'] getting value like child_name or uid .. How can i do that?
You can parse custom_data with json.loads and then access the returned dict:
>>> import json
>>> json.loads(temp['custom_data'])['child_name']
'홍설'
Note that the example data you provided is not valid Python since Python uses False instead of false.
You can simply get the values of any dictionary using the keys. So lets take it step by step:
first, lets get the dictionary -
temp['custom_data']
will give you the child dictionary, then, in order to access the items of this child dict, you can use the child keys:
temp['custom_data']['child_name']
temp['custom_data']['uid']
etc.

python json dump, how to make specify key first?

I want to dump this json to a file:
json.dumps(data)
This is the data:
{
"list":[
"one": { "id": "12","desc":"its 12","name":"pop"},
"two": {"id": "13","desc":"its 13","name":"kindle"}
]
}
I want id to be the first property after I dump it to file, but it is not. How can I fix this?
My guess is that it's because you're using a dictionary (hash-map). It's unsortable.
What you could do is:
from collections import OrderedDict
data = OrderedDict()
data['list'] = OrderedDict()
data['list']['one'] = OrderedDict()
data['list']['one']['id'] = '12'
data['list']['one']['idesc'] = ...
data['list']['two'] = ...
This makes it sorted by order of input.
It's "impossible" to know the output of a dict/hashmap because the nature (and speed) of a traditional dictionary makes the sort/access order vary depending on usage, items in the dictionary and a lot of other factors.
So you need to either pass your dictionary to a sort() function prior to sending it to json or use a slower version of the dictionary called OrderedDict (see above).
Many thanks goes out to #MarcoNawijn for checking the source of JSON that does not honor the sort structure of the dictionary, which means you'll have to build the JSON string yourself.
If the parser on the other end of your JSON string honors the order (which i doubt), you could pass this to a function that builds a regular text-string representation of your OrderedDict and formatting the string as per JSON standards. This will however take up more time than I have at this moment since i'm not 100% certain of the RFC for JSON strings.
You shouldnt worry about the order in which json is saved. The order will be changed when dumping. Better look at these too. JSON order mixed up
and
Is the order of elements in a JSON list maintained?

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

Categories