Search code examples
jmespath

jmespath extract a key from a list which is not json


I am trying to extract a piece of text from a list.
The list is something like this

[{'texts': [{'language': {'isoCode': 'it', 'name': 'Italian'},
    'text': 'CATETERI VENOSI CENTRALI CON ACCESSO PERIFERICO MULTILUME',
    'allLanguagesApplicable': None},
   {'language': {'isoCode': 'fr', 'name': 'French'},
    'text': 'CATHÉTERS VEINEUX CENTRAUX MULTILUMIÈRES PAR ABORD PÉRIPHÉRIQUE',
    'allLanguagesApplicable': None},
   {'language': {'isoCode': 'en', 'name': 'English'},
    'text': 'CENTRAL I.V. MULTI-LUMEN CATHETERS, PERIPHERAL ACCESS',
    'allLanguagesApplicable': None}]}]

I need to extract the text where language.isoCode is en.

But the JMESPath query is alluding me for some reason.

I want the output as

CENTRAL I.V. MULTI-LUMEN CATHETERS, PERIPHERAL ACCESS

This is my try

jmespath.search("[*].texts[?language.isoCode == 'en'].text[]", temp_json)
['CENTRAL I.V. MULTI-LUMEN CATHETERS, PERIPHERAL ACCESS']

But, I want the text only not an array.


Solution

  • You need to stop the filter projection created by [?language.isoCode == 'en'] in order to get the first element of that array.

    This is exaplained in details in the chapter named pipe expressions of the tutorials.

    So, you query ends up being

    [*].texts[?language.isoCode == 'en'].text[] | [0]
    

    Which gives the expected:

    "CENTRAL I.V. MULTI-LUMEN CATHETERS, PERIPHERAL ACCESS"