json-extractor.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. # Copyright 2014 The Kubernetes Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # This is a very simple utility that reads a JSON document from stdin, parses it
  16. # and returns the specified value. The value is described using a simple dot
  17. # notation. If any errors are encountered along the way, an error is output and
  18. # a failure value is returned.
  19. from __future__ import print_function
  20. import json
  21. import sys
  22. def PrintError(*err):
  23. print(*err, file=sys.stderr)
  24. def main():
  25. try:
  26. obj = json.load(sys.stdin)
  27. except Exception, e:
  28. PrintError("Error loading JSON: {0}".format(str(e)))
  29. if len(sys.argv) == 1:
  30. # if we don't have a query string, return success
  31. return 0
  32. elif len(sys.argv) > 2:
  33. PrintError("Usage: {0} <json query>".format(sys.args[0]))
  34. return 1
  35. query_list = sys.argv[1].split('.')
  36. for q in query_list:
  37. if isinstance(obj, dict):
  38. if q not in obj:
  39. PrintError("Couldn't find '{0}' in dict".format(q))
  40. return 1
  41. obj = obj[q]
  42. elif isinstance(obj, list):
  43. try:
  44. index = int(q)
  45. except:
  46. PrintError("Can't use '{0}' to index into array".format(q))
  47. return 1
  48. if index >= len(obj):
  49. PrintError("Index ({0}) is greater than length of list ({1})".format(q, len(obj)))
  50. return 1
  51. obj = obj[index]
  52. else:
  53. PrintError("Trying to query non-queryable object: {0}".format(q))
  54. return 1
  55. if isinstance(obj, str):
  56. print(obj)
  57. else:
  58. print(json.dumps(obj, indent=2))
  59. if __name__ == "__main__":
  60. sys.exit(main())