Hu66s
Hu66s

Reputation: 53

How to iterate to json object and gets its array using robot framework

Successfully stored it to array list

I want to Iterate on Locationlist and get its country type and bikeList bike type and text.

    {
"addedToList": {
    "locationList": [
        {
            "countryType": "US"
            "LineList": [
                {
                    "Text": "thequickbrownfoxjumps over the lazy dog"
                }
            ]
        }
    ],
    "bikeList": [
        {
            "BikeType": "road"
            "LineList": [
                {
                    "Text": "text"

                }
            ]
        }
    ]
},
"addedLine": "2"
}

Upvotes: 0

Views: 2095

Answers (3)

Nils Ba.-Ty.
Nils Ba.-Ty.

Reputation: 46

You can also do this without the JSONLibrary by just using json.loads via the Evaluate Keyword

*** Variables ***
${MY_JSON}    {"addedToList":{"locationList":[{"countryType":"US","LineList":[{"Text":"thequickbrownfoxjumps over the lazy dog"}]}],"bikeList":[{"BikeType":"road","LineList":[{"Text":"text"}]}]},"addedLine":"2"}

*** Test Cases ***
Test For Json
    ${json}    Evaluate   json.loads('''${MY_JSON}''')    json
    FOR   ${loc_list}    IN    @{json['addedToList']['locationList']}
        Log    countryType: ${loc_list["countryType"]}  console=True
    END
    FOR   ${bike_list}    IN    @{json['addedToList']['bikeList']}
        Log    BikeType: ${bike_list["BikeType"]}  console=True
    END

Upvotes: 1

Ji Bin
Ji Bin

Reputation: 531

If want with pure robotframework, you could check robotframework-jsonlibrary

An example robot case to access your json file's country:

*** Settings ***
Library     JSONLibrary
Library     Collections

*** Test Cases ***
Test For Json
    ${json_obj} =   Load JSON From File     example.json
    ${countries} =  Get Value From Json     ${json_obj}     $..countryType
    @{countries} =  Convert To List         ${countries}
    FOR     ${country}     IN      @{countries}
        Log To Console      ${country}
    END

And what's more, if you're familiar with extending robot's keywords with python, you could also write your own keywords by python.

Upvotes: 1

Hu66s
Hu66s

Reputation: 53

use JSON [https://goessner.net/articles/JsonPath/][query selector] $..locationList[?(@.countryType)].countryType to filter all country type under selected object

Upvotes: 0

Related Questions