jsqry es mejor que jq

En mi último artículo sobre Habré, escribí sobre la biblioteca Jsqry , que proporciona un lenguaje de consulta (DSL) simple y conveniente para objetos JSON. Ha pasado mucho tiempo desde entonces y la biblioteca también se ha desarrollado. Otro motivo de orgullo: la biblioteca tiene una cobertura de código del 98% por pruebas. Sin embargo, este artículo no se trata exclusivamente de ella.



Creo que muchos de ustedes están familiarizados con la herramienta jq, que es prácticamente el estándar de facto para trabajar con JSON en la línea de comandos y scripts. También fui un usuario activo de él. Pero estaba constantemente preocupado por la complejidad injustificada y la sintaxis poco intuitiva de las consultas de esta utilidad. Y no solo yo, aquí hay algunas citas de hacker news :



He estado usando jq durante años y todavía no puedo hacer que funcione como esperaba.



Tengo el mismo problema con jq. Necesito usar mi fu de google para descubrir cómo hacer algo más que una simple selección.



No sé cuál sería el término, modelo mental, pero no puedo hacer que jq haga clic. Sobre todo porque solo lo necesito de vez en cuando. Es frustrante para mí porque parece bastante poderoso.



Sé que podría ser una opinión disidente aquí, pero nunca puedo entenderlo jq. Puedo manejar jq ., jq .fooy jq -r, pero más allá de eso, el DSL es simplemente opaco a mí.



Digámoslo: jq es una herramienta increíble, pero el DSL es simplemente malo.



Sí, encuentro que jq es similar a escribir expresiones regulares: siempre tengo que buscar la sintaxis, solo hacer que funcione después de cierta confusión de por qué mis patrones no coinciden, luego lo olvido todo en unos días, así que tengo que volver a aprenderlo más tarde.

En resumen, probablemente ya lo hayas adivinado. Tengo una idea, ¿por qué no convertir mi biblioteca JS en un ejecutable de línea de comandos?Aquí hay un matiz. La biblioteca está escrita en JS y su DSL también se basa en JS. Esto significa que debemos encontrar una manera de empaquetar el programa y algo de tiempo de ejecución JS en un archivo ejecutable autónomo.



jsqry - edición GraalVM



Para aquellos que aún no están en el tema (¿realmente todavía existen? OO), permítanme recordarles que GraalVM es una JVM tan mejorada de Oracle con características adicionales, las más notables de las cuales son:



  1. JVM — Java, Javascript, Python, Ruby, R, ..
  2. AOT- — Java
  3. JIT- Java.


Graal , , -.



, 1. 2. — JS .



https://github.com/jsqry/jsqry-cli. , — deprecated. , . , 99 . - . , jq 3.7 Linux 64.



.



, Java + JS GraalVM.





App.java. , java- Apache Commons CLI.



java- javascript , src/main/resources.



. -



scripts.add(new String(Files.readAllBytes(Paths.get(jsFileResource.toURI()))));


( , native-image)



java.nio.file.FileSystemNotFoundException: Provider "resource" not installed


"" InputStream



scripts.add(new Scanner(jsFileResource.openStream()).useDelimiter("\\A").next());


, 100% Java .



java.awt.Graphics. GraalVM AWS Lambda .



jsqry — QuickJS edition



- JS QuickJS . qjsc . ES2020. !



, CLI- jsqry: https://github.com/jsqry/jsqry-cli2.

.



, jsqry?



jsqry ( jq) JSON "" DSL.



— JS jsqry .







$ echo '[{"name":"John","age":30},
         {"name":"Alice","age":25},
         {"name":"Bob","age":50}]' | jsqry 'name'
[
  "John",
  "Alice",
  "Bob"
]




$ echo '[{"name":"John","age":30},
         {"name":"Alice","age":25},
         {"name":"Bob","age":50}]' | jsqry -1 'name'
"John"




$ echo '[{"name":"John","age":30},{"name":"Alice","age":25},{"name":"Bob","age":50}]' \
    | jsqry '[ _.age>=? && _.name.toLowerCase().startsWith(?) ]' --arg 30 --arg-str joh 
[
  {
    "name": "John",
    "age": 30
  }
]


JSON pretty-printer



$ echo '[{"name":"John","age":30},{"name":"Alice","age":25},{"name":"Bob","age":50}]' \
 | jsqry
[
  {
    "name": "John",
    "age": 30
  },
  {
    "name": "Alice",
    "age": 25
  },
  {
    "name": "Bob",
    "age": 50
  }
]


JSON . !



-



2, 100, 2 . . DSL.



$ echo '[1,2,3,4,5]' | jsqry '[_>2] {_+100} s(-_) [-2:]'
[
  104,
  103
]


JS



jsqry JS- 1 , JS !



$ echo '["HTTP://EXAMPLE.COM/123", 
         "https://www.Google.com/search?q=test", 
         "https://www.YouTube.com/watch?v=_OBlgSz8sSM"]' \
 | jsqry '{ _.match(/:\/\/([^\/]+)\//)[1].toLowerCase() }'
[
  "example.com",
  "www.google.com",
  "www.youtube.com"
]


help-



$ jsqry
jsqry ver. 0.1.2
Usage: echo $JSON | jsqry 'query'
 -1,--first     return first result element
 -h,--help      print help and exit
 -v,--version   print version and exit
 -c,--compact   compact output (no pretty-print)
 -u,--unquote   unquote output string(s)
 -as ARG,
 --arg-str ARG  supply string query argument
 -a ARG,
 --arg ARG      supply query argument of any other type


jq



jq jsqry .





( ): 0.1.2.



, Linux x64 . , . .



, :



$ sudo bash -e -c "
wget https://github.com/jsqry/jsqry-cli2/releases/download/v0.1.2/jsqry-linux-amd64 -O/usr/local/bin/jsqry
chmod +x /usr/local/bin/jsqry
echo \"jsqry \$(jsqry -v) installed successfully\" 
"


CLI-



GitHub - . - , . , CLI- , . , , , — .



"bash unit testing" BATS, ShellSpec, Bach , , ( 14 ), tush, .



tush



$ command --that --should --execute correctly
| expected stdout output

$ command --that --will --cause error
@ expected stderr output
? expected-exit-code


tush $, |, @ ? — , . , $ , diff. , diff . :



$ /bin/bash /home/xonix/proj/jsqry-cli2/tests.sh
--- tests.tush expected
+++ tests.tush actual
@@ -1,5 +1,5 @@
 $ jsqry -v
-| 0.1.2
+| 0.1.1

 $ jsqry -h
 | jsqry ver. 0.1.1
!!! TESTS FAILED !!!




tests.tush.



, , .



GitHub Action, , :



Construye y prueba





JSON



JSON . zvakanaka/color-json , StackOverflow . jq. , null .



captura de pantalla



, .



npm- QuickJS



npm- jsqry . package.json . npm i. prepare-for-qjs.py, nodejs ES, QuickJS. jsqry-cli.js.



UTF-8 QuickJS



QuickJS stdin. , , QuickJS, . , UTF-8 JS-. , , QuickJS: twardoch/svgop.





build.sh.



"" , .



tests.sh. , , .



build.sh QuickJS, tests.sh tush. — .



. ls -lh jsqry . , , CLI- . , — , QuickJS.



652 KB. , , JS.





jq. .




All Articles