gpt4 book ai didi

json - 如何将bash和curl与转义的json一起使用?

转载 作者:行者123 更新时间:2023-12-03 00:42:15 25 4
gpt4 key购买 nike

如果我一个接一个地执行它们,那么下面的两个命令可以在脚本外部完美地工作,但是,如果将它们放在bash脚本中,则可以完美地工作。他们失败了。

DATA="{\"size\":500,\"sort\":{\"@timestamp\":\"desc\"},\"query\":{\"filtered\":{\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"tx.traceId: AIP1447283489-6 AND event: published_notification AND attempt: 1\"}},\"filter\":{\"bool\":{\"must\":[{\"range\":{\"@timestamp\":{\"gte\":1420099200000,\"lte\":1451635199999}}}],\"must_not\":[]}}}},\"highlight\":{\"pre_tags\":[\"@kibana-highlighted-field@\"],\"post_tags\":[\"@\/kibana-highlighted-field@\"],\"fields\":{\"*\":{}}},\"aggs\":{\"2\":{\"date_histogram\":{\"field\":\"@timestamp\",\"interval\":\"1w\",\"pre_zone\":\"-08:00\",\"pre_zone_adjust_large_interval\":true,\"min_doc_count\":0,\"extended_bounds\":{\"min\":1420099200000,\"max\":1451635199999}}}},\"fields\":[\"*\",\"_source\"],\"script_fields\":{},\"fielddata_fields\":[\"log.timestamp\",\"@timestamp\",\"val\"]}"

curl -s -XPOST http://username:password@url/elasticsearch/index-*/_search -d $DATA | jq '.hits.hits[0].fields."log.timestamp"[0]'

通过使用set -x,我发现执行的最终curl命令是:
curl -s -XPOST 'http://username:password@url/elasticsearch/index-*/_search' -d '{"size":500,"sort":{"@timestamp":"desc"},"query":{"filtered":{"query":{"query_string":{"analyze_wildcard":true,"query":"tx.traceId:' AIP1447283489-6 AND event: published_notification AND attempt: '1"}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":1420099200000,"lte":1451635199999}}}],"must_not":[]}}}},"highlight":{"pre_tags":["@kibana-highlighted-field@"],"post_tags":["@\/kibana-highlighted-field@"],"fields":{"*":{}}},"aggs":{"2":{"date_histogram":{"field":"@timestamp","interval":"1w","pre_zone":"-08:00","pre_zone_adjust_large_interval":true,"min_doc_count":0,"extended_bounds":{"min":1420099200000,"max":1451635199999}}}},"fields":["*","_source"],"script_fields":{},"fielddata_fields":["log.timestamp","@timestamp","val"]}'

并且,如果您发现有多余的单引号,例如:'附加在“query”的值周围。如您所见:
"query":"tx.traceId:' AIP1447283489-6 AND event: published_notification AND attempt: '1"

到底发生了什么,如何在脚本中将此json与这两个命令一起使用?

最佳答案

您没有在命令中引用$DATA

curl -s -XPOST http://username:password@url/elasticsearch/index-*/_search -d $DATA

因此 $DATA在执行参数扩展后会进行分词(甚至更多)。您的 $DATAquery的值中包含空格,因此将其拆分并分成多个参数。你想要的是
curl -s -XPOST http://username:password@url/elasticsearch/index-*/_search -d "$DATA"

另外,我个人的建议是用单引号将JSON字符串引号,并在需要文字单引号时使用 '\''。在 shell 中用双引号引起来JSON只会使结果无法读取...

关于json - 如何将bash和curl与转义的json一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33683171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com