convert a json string to python object

Question:

Is it possible to convert a json string (for e.g. the one returned from the twitter search json service) to simple string objects. Here is a small representation of data returned from the json service:

{
results:[...],
"max_id":1346534,
"since_id":0,
"refresh_url":"?since_id=26202877001&q=twitter",
.
.
.
}

Lets say that I somehow store the result in some variable, say, obj. I am looking to get appropriate values like as follows:

print obj.max_id
print obj.since_id

I’ve tried using simplejson.load() and json.load() but it gave me an error saying 'str' object has no attribute 'read'

Asked By: deostroll

||

Answers:

I’ve tried using simplejson.load() and json.load() but it gave me an error saying 'str' object has no attribute 'read'

To load from a string, use json.loads() (note the ‘s’).

More efficiently, skip the step of reading the response into a string, and just pass the response to json.load().

Answered By: Ben James

if you don’t know if the data will be a file or a string…. use

import StringIO as io
youMagicData={
results:[...],
"max_id":1346534,
"since_id":0,
"refresh_url":"?since_id=26202877001&q=twitter",
.
.
.
}

magicJsonData=json.loads(io.StringIO(str(youMagicData)))#this is where you need to fix
print magicJsonData
#viewing fron the center out...
#youMagicData{}>str()>fileObject>json.loads
#json.loads(io.StringIO(str(youMagicData))) works really fast in my program and it would work here so stop wasting both our reputation here and stop down voting because you have to read this twice 

from https://docs.python.org/3/library/io.html#text-i-o

json.loads from the python built-in libraries, json.loads requires a file object and does not check what it’s passed so it still calls the read function on what you passed because the file object only gives up data when you call read(). So because the built-in string class does not have the read function we need a wrapper. So the StringIO.StringIO function in short, subclasses the string class and the file class and meshing the inner workings hears my low detail rebuild https://gist.github.com/fenderrex/843d25ff5b0970d7e90e6c1d7e4a06b1
so at the end of all that its like writing a ram file and jsoning it out in one line….

Answered By: Rex Fender Baird
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.