HCE Project Python language Distributed Tasks Manager Application, Distributed Crawler Application and client API bindings.  2.0.0-chaika
Hierarchical Cluster Engine Python language binding
json-field.py
Go to the documentation of this file.
1 #!/usr/bin/python
2 
3 
4 '''
5 HCE project, Python bindings, Distributed Crawler application.
6 Application level constants and enumerations.
7 
8 @package: dc
9 @author bgv bgv.hce@gmail.com
10 @link: http://hierarchical-cluster-engine.com/
11 @copyright: Copyright © 2013-2014 IOIX Ukraine
12 @license: http://hierarchical-cluster-engine.com/license/
13 @since: 0.1
14 '''
15 
16 
17 import ppath
18 from ppath import sys
19 
20 import hashlib
21 from optparse import OptionParser
22 import json
23 import base64
24 
25 parser = OptionParser()
26 parser.add_option("-f", "--field", type="string",
27  help="json field pathname semicolon delimited, for example response:error_code", dest="field")
28 parser.add_option("-b", "--base64", type="string",
29  help="base64 decode value", dest="base64")
30 
31 
32 if __name__ == "__main__":
33  options, arguments = parser.parse_args()
34 
35  if options.__dict__["field"]:
36  fieldNameStr = options.__dict__["field"]
37  if options.__dict__["base64"] is not None:
38  base64Decode = int(options.__dict__["base64"])
39  else:
40  base64Decode = 0
41 
42  if fieldNameStr is not None and fieldNameStr != "":
43  fieldNamesList = fieldNameStr.split(":")
44  jsonString = sys.stdin.read()
45 
46  if jsonString is not None and jsonString != "":
47  try:
48  #jsonDic = json.loads(jsonString.decode('utf-8'))
49  jsonDic = json.loads(str(jsonString))
50 
51  retVal = jsonDic
52  for fieldName in fieldNamesList:
53  if isinstance(retVal, dict):
54  for jsonName in retVal:
55  if fieldName == jsonName:
56  retVal = retVal[fieldName]
57  break
58  else:
59  if isinstance(retVal, list):
60  if fieldName == "__LEN__":
61  retVal = str(len(retVal))
62  break
63  else:
64  index = int(fieldName)
65  if len(retVal) > index:
66  retVal = retVal[index]
67  else:
68  retVal = ""
69  else:
70  if fieldName == "__LEN__":
71  retVal = -1
72  break
73  if base64Decode and fieldName != "__LEN__":
74  retVal = base64.b64decode(str(retVal))
75  else:
76  retVal = retVal
77 
78  if isinstance(retVal, dict):
79  retVal = json.dumps(retVal)
80 
81  if isinstance(retVal, unicode):
82  sys.stdout.write(retVal)
83  else:
84  sys.stdout.write(str(retVal))
85  except Exception, e:
86  sys.stdout.write("Json parsing or item select error : " + str(e) + "\n")
87  else:
88  sys.stdout.write("Input json is empty.\n")
89  else:
90  sys.stdout.write("Json field name [" + str(fieldNameStr) + "] error!\n")
91  else:
92  sys.stdout.write("Mandatory argument(s) not specified, try -h to get detailed descriptions.\n")
93 
94  sys.stdout.flush()
95 
96 
97