Guest User

Untitled

a guest
Jun 19th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. #!/usr/bin/env bash
  2. jsonLoadFromStdIn="json.load(sys.stdin)"
  3. loopOverItems=false
  4. loopJsonOperation=""
  5.  
  6. __doJsonOperation() {
  7. json="$1"
  8. operation="$2"
  9.  
  10. operationWithJsonLoad=${operation/__JSON__/$jsonLoadFromStdIn}
  11.  
  12. echo "${json}" | python -c "import sys, json; print ${operationWithJsonLoad}"
  13. }
  14.  
  15. __convertJsonPathToOperation() {
  16. jsonPath="$1"
  17.  
  18. jsonPath="${jsonPath:1}"
  19. jsonPath="${jsonPath//[/.[}"
  20.  
  21. IFS='.' read -ra jsonPathParts <<< "${jsonPath}"
  22.  
  23. loopOverItems=false
  24. loopJsonOperation=""
  25. jsonOperation="__JSON__"
  26.  
  27. for jsonPathPart in "${jsonPathParts[@]}"; do
  28. if [ "${jsonPathPart:0:1}" = "[" ] && [ "${jsonPathPart: -1}" = "]" ]; then
  29. # handle array lookups
  30.  
  31. if [ "${jsonPathPart}" = "[*]" ]; then
  32. # act on all items in array
  33. loopOverItems=true
  34. else
  35. # get item at index in array
  36. if [ "${loopOverItems}" = false ]; then
  37. jsonOperation="${jsonOperation}${jsonPathPart}"
  38. else
  39. loopJsonOperation="${loopJsonOperation}${jsonPathPart}"
  40. fi
  41. fi
  42. elif [ "${jsonPathPart}" = "length()" ]; then
  43. # get length of array
  44. if [ "${loopOverItems}" = false ]; then
  45. jsonOperation="len(${jsonOperation})"
  46. else
  47. loopJsonOperation="${loopJsonOperation}.__len__()"
  48. fi
  49. elif [ ! -z "${jsonPathPart}" ]; then
  50. # get object property
  51. if [ "${loopOverItems}" = false ]; then
  52. jsonOperation="${jsonOperation}['${jsonPathPart}']"
  53. else
  54. loopJsonOperation="['${loopJsonOperation}${jsonPathPart}']"
  55. fi
  56. fi
  57. done
  58.  
  59. echo "jsonOperation=\"${jsonOperation}\"; loopOverItems=${loopOverItems}; loopJsonOperation=\"${loopJsonOperation}\""
  60. }
  61.  
  62. json-path-query() {
  63. json="$1"
  64. jsonPath="$2"
  65.  
  66. if [ -z "${json}" ] || [ -z "${jsonPath}" ]; then
  67. >&2 echo "Usage: $0 json jsonPath"
  68. return 1
  69. fi
  70.  
  71. eval $(__convertJsonPathToOperation "${jsonPath}")
  72.  
  73. if [ "${loopOverItems}" = false ]; then
  74. __doJsonOperation "${json}" "${jsonOperation}"
  75. fi
  76.  
  77. numItems="$(__doJsonOperation "${json}" "len(${jsonOperation})")"
  78.  
  79. for ((i=0; i < ${numItems}; i++)); do
  80. __doJsonOperation "${json}" "${jsonOperation}[${i}]${loopJsonOperation}"
  81. done
  82. }
Add Comment
Please, Sign In to add comment