I'm trying to get a curl response between {}. I have found and tested a regex command that works files with Sublime or an online tester.
The problem occurs when I try to execute it with grep from MacOS. I have installed the grep from the brew library, but even though the installation occurred 100%, the command doesn't work. Deleting all break lines of file/response (performing debug), the command works! But in my case, the curl response comes with break lines, so I should be able to handle it.
Could someone tell me why it is occurring with MacOS and how I can solve it?
Curl response:
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"
}
I want to get only the following lines:
{
"detail": "Cluster asdasdasd cannot be created in a paused state.",
"error": 400,
"errorCode": "CANNOT_CREATE_PAUSED_CLUSTER",
"parameters" : [ "asdasdasd" ],
"reason": "Bad Request"
}
My regexs:
{([\S\s] )}
{[^{}]*}
Sublime response:
regextester.com result:
CodePudding user response:
Better use jq.
Your input are plain JSON.
Example to retrieve errorCode:
curl ...... | jq '.errorCode'
jqis likesedforJSONdata - you can use it to slice and filter and map and transform structured data with the same ease thatsed,awk,grepand friends let you play with text.
Or gron
curl ...... | gron | awk -F' = ' '/^json.errorCode /{print $2}'
To install it:
go install github.com/tomnomnom/gron@latest
CodePudding user response:
I have converted the curl command to python code. It is easier to handle with the response.
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)


