简体   繁体   中英

Robot Framework how to count item list in JSON

I would like to count item "Start" from JSON APIs on Robot Framework

{
    "result": {
        "api": "xxx",
        "timestamp": "14:41:18",
        "series": [
            {
                "series_code": "test",
                "series_name_eng": "test",
                "unit_eng": "t",
                "series_type": "e",
                "frequency": "s",
                "last_update_date": "2020",
                "observations": [
                    {
                        "start": "2020-01",
                        "value": "999"
                    },
                    {
                        "start": "2020-02",
                        "value": "888"
                    },
                    {
                        "start": "2020-03",
                        "value": "777"
                    },
                ]
            }

I use this not working

${json_string}    Get File        ./example.json
 ${json_object}    evaluate        json.loads('''${json_string}''')    json    
 #${value}=    get value from json    ${json_object}    $.result.series[0].observations
 ${x_count}    Get Length    ${json_object["$.result.series[0].observations"]}

Could you please help guide to for how?

The Json provided in the example above is not valid one. That will need to be fixed by closing series array ] then close the results object } and then close the outer object } Valid json will look like this -

${Getjson}=         {"result":{"api":"xxx","timestamp":"14:41:18","series":[{"series_code":"test","series_name_eng":"test","unit_eng":"t","series_type":"e","frequency":"s","last_update_date":"2020","observations":[{"start":"2020-01","value":"999"},{"start":"2020-02","value":"888"},{"start":"2020-03","value":"777"}]}]}}

You were close with this jsonpath $.result.series[0].observations . The correct one is in below example -

${json}=          Convert String to JSON    ${Getjson}
@{Start}=         Get Value From Json     ${json}            $.result.series[?(@.observations)].observations[?(@.start)].start
${length}         Get length          ${Start}   
log               ${length}

Output:-

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM