json MacOS正则表达式grep获取花括号之间的值

inkz8wg9  于 2023-01-14  发布在  Mac
关注(0)|答案(2)|浏览(116)

我正在尝试在{}之间获得curl响应。我已经找到并测试了一个regex命令,该命令可以使用Sublime或在线测试器处理文件。
当我尝试从MacOS中使用grep执行时出现了这个问题。我已经从brew库安装了grep,但是即使100%安装成功,命令也不起作用。删除file/response的所有中断行(执行调试),命令起作用了!但是在我的例子中,curl响应带有中断行,所以我应该能够处理它。
有人能告诉我为什么它会发生在MacOS上,以及我如何解决它吗?
curl React:

HTTP/2 401 
www-authenticate: Digest realm="MMS Public API", domain="", nonce="8878t9jXCP7+", algorithm=MD5, qop="auth", stale=false
content-type: application/JSON
content-length: 106
x-envoy-upstream-service-time: 3
date: Fri, 13 Jan 2023 17:04:03 GMT
server: envoy

HTTP/2 400 
date: Fri, 13 Jan 2023 17:04:04 GMT
strict-transport-security: max-age=31536000; include subdomains;
referrer-policy: strict-origin-when-cross-origin
x-permitted-cross-domain-policies: none
x-content-type-options: nosniff
content-type: application/json
x-frame-options: DENY
content-length: 200
x-envoy-upstream-service-time: 23
server: envoy

{
  "detail": "Cluster asdasdasd cannot be created in a paused state.",
  "error": 400,
  "errorCode": "CANNOT_CREATE_PAUSED_CLUSTER",
  "parameters" : [ "asdasdasd" ],
  "reason": "Bad Request"
}

我只想得到以下几行:

{
      "detail": "Cluster asdasdasd cannot be created in a paused state.",
      "error": 400,
      "errorCode": "CANNOT_CREATE_PAUSED_CLUSTER",
      "parameters" : [ "asdasdasd" ],
      "reason": "Bad Request"
    }

我的正则表达式:

{([\S\s]+)}
{[^{}]*}

卓越响应:

regextester.com :

5jdjgkvh

5jdjgkvh1#

最好使用jq

您的输入是普通的JSON
检索errorCode的示例:

curl ...... | jq '.errorCode'

jq类似于JSON数据的sed-您可以使用它来切片、过滤、Map和转换结构化数据,就像sedawkgrep和friends让您玩文本一样轻松。

gron

curl ...... | gron | awk -F' = ' '/^json.errorCode /{print $2}'

要安装它:

go install github.com/tomnomnom/gron@latest
cvxl0en2

cvxl0en22#

我已经把curl命令转换成了python代码,这样响应就更容易处理了。

import requests
from requests.auth import HTTPDigestAuth

headers = {
    'Content-Type': 'application/json',
}

params = {
    'pretty': 'true',
}

json_data = {
    'autoScaling': {
        'diskGBEnabled': True,
    },
    'backupEnabled': False,
    'paused': True,
    'name': 'sdasdasd',
    'providerSettings': {
        'providerName': 'AWS',
        'instanceSizeName': 'M10',
        'regionName': 'US_EAST_2',
    },
}

response = requests.post(
    'https://cloud.mongodb.com/api/atlas/v1.0/groups/999999999999/clusters',
    params=params,
    headers=headers,
    json=json_data,
    auth=HTTPDigestAuth('user', 'password'),
)

print(response.content)

相关问题