From f16fa56a48c26ae67e8b26f09e1af4768d084e83 Mon Sep 17 00:00:00 2001 From: andig Date: Mon, 23 Feb 2015 14:05:44 +0100 Subject: [PATCH] Add jsonclient for HTTP access to json datasources --- misc/tools/jsonclient | 75 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 misc/tools/jsonclient diff --git a/misc/tools/jsonclient b/misc/tools/jsonclient new file mode 100644 index 000000000..38ed0074d --- /dev/null +++ b/misc/tools/jsonclient @@ -0,0 +1,75 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# @copyright Copyright (c) 2011, The volkszaehler.org project +# @license http://www.opensource.org/licenses/gpl-license.php GNU Public License +# Author Andreas Götz 2015 + +# +# This file is part of volkzaehler.org +# +# volkzaehler.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# any later version. +# +# volkzaehler.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with volkszaehler.org. If not, see . +# + + +import argparse +import ConfigParser +import urllib +import urllib2 +import os +import json +version="0.1"; + +parser = argparse.ArgumentParser(description='A python client for json data sources'); +parser.add_argument('--url', action='store', help="url of the data source"); +parser.add_argument('-e', '--eval', action='store', help="get comma-separated attribute from json response (use @prop=value to filter arrays)\n(Example: entity,@uuid=4,0,type will extract the type from a json string: {entity:[{uuid:4,type=\"power\"...}]})"); +parser.add_argument('-j', '--json', action='store', help="send json request"); +args = parser.parse_args(); + +url=args.url; +if (url is None): + print "ERROR: Please specify an url!"; + exit(1); +req = urllib2.Request(url) +req.add_header('User-agent', 'jsonclient/$version') +try: + if (args.json): + req.add_header('Content-Type', 'application/json'); + f=urllib2.urlopen(url, args.json); + else: + f=urllib2.urlopen(url); + jsonstr=f.read(); + if (args.eval is None): + print jsonstr; + else: + obj=json.loads(jsonstr); + for ev in args.eval.split(",") : + if (isinstance(obj,(list,tuple))): + try: + ev=int(ev) # array access + except: + pass + try: + obj=obj[ev] + except TypeError: + # try @property=value notation + (prop,val)=ev[1:].split("=") # strip @ + obj=[el for el in obj if (prop in el and el[prop] == val)] + except KeyError: + print "Key: "+ev+" not found in str: "+jsonstr; + print obj; + exit(0); +except urllib2.HTTPError,error: + print error.read(); + exit(1);