JMESPath - Joining items in a nested array
Asked Answered
W

1

5

I have a JSON

{
"key": "processId-29231",
"fields": {
    "attachment": [
        {
            "id": "79572",
            "filename": "File1.png"
        },
        {
            "id": "74620",
            "filename": "File2.docx"
        },
        {
            "id": "79072",
            "filename": "File3.xlsx"
        }
    ]
  }
}

I need to restructure it to this

{
"processId": "processId-29231",
"attachments": [

               "https://example.com/files/79572/File1.png",
               "https://example.com/files/79572/File2.docx",
               "https://example.com/files/79572/File1.xlsx",
                ]
    }

I could make this work with a specific array index

{processID:key,attachments:join('',['https://example.com/files/',fields.attachment[1].id,'/',fields.attachment[1].filename])}

which yields this result

{
 "processID": "processId-29231",
 "attachments": "https://example.com/files/74620/File2.docx"
}

I tried this without array index in two ways

this

 {processID:key,attachments:join('',['https://example.com/',fields.attachment[].id,'/',fields.attachment[].filename])}

and this

{processID:key,attachments:join('', ['https://example.com/',fields.attachment[*].id,'/',fields.attachment[*].filename])}

but that did not help.

Any tips on how this can be solved?

Waistline answered 30/5, 2018 at 1:3 Comment(0)
I
8

You need to apply the function to each element of the array and access the current node via @

{processID:key,attachments: fields.attachment[].join('',['https://example.com/files/', @.id, '/', @.filename])}

http://jmespath.org/specification.html#functions

Isar answered 30/5, 2018 at 1:30 Comment(4)
Thanks so much. This really helped.Waistline
On a related note. Some of the file names have spaces for example "example.com/files/74620/File with a space in the name.docx" and the resulting JSON doesn't show the file name as a hyperlink. Any thoughts on how this can be fixed? I'm going to experiment with replacing spaces with a '+'.Waistline
you have to encode to url then, jmespath does not have a built function for that, so you will have to do that wherever you are retrieving the resultIsar
I thought so too. Your help is much appreciated.Waistline

© 2022 - 2024 — McMap. All rights reserved.