如何使用jq从json对象的数组中的键中提取值?

问题描述

我正在编写一个需要进行两次调用的bash脚本,第二次调用需要来自第一次调用的json响应中的值。 但是,当我尝试检索此值时出现错误

jq:错误:无法打开文件.............无效的参数

我已经在浏览器中检查了我的jq查询,并且工作正常。 这是我的脚本示例。

api_key="key1"
app_key="key2"

response=$(curl -X POST \
-H 'Content-Type: application/json' \
-H "DD-API-KEY: ${api_key}" \
-H "DD-APPLICATION-KEY: ${app_key}" \
-d '{
    "tests": [
        {
            "public_id": "abc-123-xyz","locations": ["aws:eu-west-2"]
         
        }
    ]
}' "https://URL")

resultId=$(jq '.results[].result_id' $response)

curl -G \
    "https://URL" \
    -H "DD-API-KEY: ${api_key}" \
    -H "DD-APPLICATION-KEY: ${app_key}" \
    -d "result_ids=[$resultId]"

这是json响应的示例

{
    "results": [
        {
            "result_id": "1234","public_id": "abc-123-xyz","location": 1
        }
    ],"triggered_check_ids": [
        "abc-123-xyz"
    ],"locations": [
        {
            "is_active": boolean,"region": "Somewhere","display_name": "A1","id": 1,"name": "A1"
        },{
            "is_active": boolean,"region": "Somewhere else","display_name": "B2","id": 2,"name": "B2"
        }
    ]
}

解决方法

shell变量 /** * This integration Test requires the following external dependencies to run: * 1. MySQL */ @ActiveProfiles("test") @ExtendWith(SpringExtension.class) @SpringBootTest(classes = Application.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CommonRepositoryITest { @PersistenceContext private EntityManager entityManager; @Autowired private PhotoRepository photoRepository = null; @Test public void conditionalFindAllTest() { //Data Setup String title = "BATMAN"; String size = "300*300"; List<Photo> photos = new ArrayList<>(); for (int i = 0; i < 50; i++) { Photo photo = Photo.builder(). id(UUID.randomUUID().toString()). title(title). size("300*300"). thumbnailUrl("http://localhost:8080/" + UUID.randomUUID().toString()). url("http://localhost:8080/" + UUID.randomUUID().toString()). build(); photos.add(photo); } photoRepository.saveAll(photos); //data validate Map<String,Object> conditionsToApply = new HashMap<>(); conditionsToApply.put("title",title); conditionsToApply.put("size",size); List<Photo> resultList = entityManager.createQuery("FROM Photo p WHERE p.title = :title AND p.size = :size",Photo.class). setParameter("title",title). setParameter("size",size). getResultList(); boolean hasNext; int pageNumber = 0; int limit = 25; Pageable pageRequest = PageRequest.of(pageNumber,limit); int itemsToAssert = 0; do { Slice<Photo> photosResult = commonRepository.conditionalFindAll(Photo.class,conditionsToApply,pageRequest); hasNext = photosResult.hasNext(); itemsToAssert = itemsToAssert + photosResult.getNumberOfElements(); pageNumber++; pageRequest = PageRequest.of(pageNumber,limit); } while (hasNext); Assertions.assertEquals(resultList.size(),itemsToAssert); } } 包含JSON值,而不是文件名,因此:

$response