Common utilities
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

64 行
1.9 KiB

  1. #!/usr/bin/python
  2. import sys
  3. import json
  4. import re
  5. from optparse import OptionParser
  6. parser = OptionParser()
  7. parser.add_option("-i", "--infile", dest="infile",
  8. help="read JSON from here (stdin if omitted)", metavar="FILE")
  9. parser.add_option("-o", "--outfile", dest="outfile",
  10. help="write JSON to here (stdout if omitted)", metavar="FILE")
  11. parser.add_option("-p", "--path", dest="json_path",
  12. help="JSON path to read", metavar="path.to.data")
  13. parser.add_option("-v", "--value", dest="json_value",
  14. help="Value to write to the JSON path", metavar="value")
  15. (options, args) = parser.parse_args()
  16. if options.infile is None:
  17. data = json.load(sys.stdin)
  18. else:
  19. with open(options.infile) as infile:
  20. data = json.load(infile)
  21. ref = data
  22. if options.json_value is None:
  23. # READ mode
  24. if options.json_path is not None:
  25. for token in re.split('\.', options.json_path):
  26. try:
  27. ref = ref[token]
  28. except KeyError:
  29. # JSON path does not exist, we treat that as "empty"
  30. ref = None
  31. break
  32. data = ref
  33. else:
  34. # WRITE mode
  35. if options.json_path is not None:
  36. token_path = re.split('\.', options.json_path)
  37. if len(token_path) == 0:
  38. data = options.json_value
  39. else:
  40. for token in token_path[0:-1]:
  41. try:
  42. ref = ref[token]
  43. except KeyError:
  44. # JSON path does not exist, create it
  45. ref[token] = {}
  46. ref = ref[token]
  47. ref[token_path[-1]] = options.json_value
  48. else:
  49. data = options.json_value
  50. if ref is not None:
  51. if options.outfile is None:
  52. print json.dumps(data, sys.stdout, indent=2)
  53. else:
  54. with open(options.outfile, 'w') as outfile:
  55. outfile.write(json.dumps(data, indent=2))