[PY] Best way to read JSON response?
#16
just to save other peoples time I'm still working on adjusting the examples provided. Line 128 of Martijn's link seems the best candidate for me so far, as it allows me to preserve the JSON queries in their native form (lets me test easily in the REST client) and it should also strip away the unicode junk (u'Fancy Tag') far better than any regex I write will.

TBC and thanks thus far.
Reply
#17
Nevermind. I can't seem to delete my posts anymore.
Reply
#18
OK, think I've finally got it based on Martijn's code. Main challenge is that working with a json list is quite different from working with a python dict. I'm doing this to encode to a local list, then decode and print individual elements:
Code:
json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies","params": {"properties" : ["tag","imdbnumber"], "sort": { "order": "ascending", "method": "label", "ignorearticle": true } }, "id": "libMovies"}')
   json_query = unicode(json_query, 'utf-8', errors='ignore')
   jsonobject = simplejson.loads(json_query)
   Medialist = []
   if jsonobject['result'].has_key('movies'):
        for item in jsonobject['result']['movies']:
                Medialist.append({'dbid': item.get('movieid',''),'id': item.get('imdbnumber',''),'name': item.get('label','')})
   for movie in Medialist:
           print (json.dumps(movie.get('dbid','')))
           print (json.dumps(movie.get('id','')))
           print (json.dumps(movie.get('name','')))
Reply
#19
How is it different. It's basically the same except for false, true and null.
For python coding questions first see http://mirrors.xbmc.org/docs/python-docs/
Reply
#20
Print list.namedattribute
Or
Print list[0]

Doesn't work. I have to do that item.get command to return imdbIDs.

Also, I have to use Json.dumps to get the data into a readable/write able format. All in all quite different I would say.
Reply
#21
Read my first response to your question.
For python coding questions first see http://mirrors.xbmc.org/docs/python-docs/
Reply
#22
"If you trust the source JSON is basically a python dict. "

Not exactly helpful.
Reply
#23
?

You don't see the example? Just eval the JSON source to a dict.
For python coding questions first see http://mirrors.xbmc.org/docs/python-docs/
Reply
#24
"# JSON uses true, false and null
null = None
true = True
false = False

result = eval(json_source)"

I didn't see that no. But I still don't know how to use that to help me or even how to use that to read documentation that would help.

I'm not a skilled python coder. Not even close. I can do things with batch files that may surprise even the most experienced developer, but I'm really just a network admin who is looking for a new challenge. Python is my first "proper" language, so I need a little more guidance than was perhaps initially anticipated.
Reply
#25
you tried this?
PHP Code:
for movie in Medialist:
           print 
movie.get('dbid','')
           print 
movie.get('id','')
           print 
movie.get('name',''
Read/follow the forum rules.
For troubleshooting and bug reporting, read this first
Interested in seeing some YouTube videos about Kodi? Go here and subscribe
Reply
#26
Yeah - I needed json.dumps for reading the unicode in the movie names:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb3' in position 5: ordinal not in range(128)

is what happens without it.
Reply
#27
Just wanted to say thank you to everyone who helped in this thread. I learned a lot and finally moved away from SQL queries to json in order to play by the (entirely understandable) addon rules and update my first addon. It is pitifully slow now, but it runs as a service so that's not such a big deal.

If any other newbies hit this thread facing similar challenges, have a gander a copy of my working code here.
Reply
#28
hi
i test all of source in this post but all of them not work good if it's posible for you send me sample for read JSON response ! i want's to send json command like
this command http://192.168.1.105:8080/jsonrpc?request={"jsonrpc":"2.0","method":"input.Home","id":1} from my pc and resive in my python on my xbmc

thank's if you help me
my email:[email protected]
Reply
#29
I use this:

https://github.com/jcsaaddupuy/python-xbmc

(pip install xbmc-json gets it)

and it looks like this in code:

Code:
result = xbmc.VideoLibrary.GetMovies( {"filter": {"field": "playcount", "operator": "greaterthan", "value": "0"}})
        movies_unwatched = result["result"]["movies"]
        for movie in sorted(movies_unwatched):
            result = xbmc.VideoLibrary.GetMovieDetails( {"movieid": int(movie['movieid']), "properties": ['file']})
            uri = result['result']['moviedetails']['file']
            parts = uri.split('/')
            folder = parts[-2]
            #DVDs have folders in them....
            if folder.lower()=="video_ts":
                folder = parts[-3]
            seen_movies.append(folder.encode("utf-8"))

Note that last line which deals with the unicode issues (by far the bese python/unicode article I've seen: http://blog.notdot.net/2010/07/Getting-u...-in-Python

That's really very simple I think?
Addons I wrote &/or maintain:
OzWeather (Australian BOM weather) | Check Previous Episode | Playback Resumer | Unpause Jumpback | XSqueezeDisplay | (Legacy - XSqueeze & XZen)
Sorry, no help w/out a *full debug log*.
Reply
#30
I also like that python module, far neater (and way cleverer) than the one I had started pulling together.

One point I should add is that, if your xbmc uses authentication then that code seems to give a 401 unauthorised error. If that's the case for you, then I forked the code and put in some alternative handling of authentication (https://github.com/elParaguayo/python-xb...bmcjson.py)
BBC Live Football Scores: Football scores notifications service.
script.squeezeinfo: shows what's playing on your Logitech Media Server
Reply

Logout Mark Read Team Forum Stats Members Help
[PY] Best way to read JSON response?0