使用机器人框架将对象添加到 json

Add object to json with robot framework

${json_obj}=    Load JSON From File    C:\temp\example.json
JSONLibrary.Delete Object From Json    ${json_obj}    $..address

这是删除地址的方法。

但是如果我想添加一些值的地址,该怎么做呢?

试过这个但没有添加:

${object_to_add}=    Create Dictionary    latitude=13.1234    longitude=130.1234

${json_obj}=    Add Object To Json     ${json_obj}    $..address    ${object_to_add}


{
    "firstName": "John",
    "lastName": "doe",
    "age": 26,
    "gender": "male",
    "favoriteColor": [
        "blue"
    ],
    "isMarried": false,
    
    "address": {
        "streetAddress": "naist street",
        "city": "Nara",
        "postalCode": "630-0192"
    },
    
    "phoneNumbers": [{
        "type": "iPhone",
        "number": "0123-4567-8888"
    }, {
        "type": "home",
        "number": "0123-4567-8910"
    }]
}

可能是在尝试删除“address”后,json 路径“$..address”不再存在,您将无法向其添加对象。

您可以检查主对象中是否存在“地址”键,如果不存在则使用坐标作为键值创建它

*** Settings ***
Library  JSONLibrary
Library  Collections

*** Test Cases ***
Scenario: Add Objects

    ${current_record}    Load JSON From File   C:\temp\example.json   
    Delete Object From Json   ${current_record}   $..address 

    ${coords}      Create Dictionary    latitude=13.1234   longitude=130.1234

    # Check if the "address" key is in the object
    ${is_address_key}  Run Keyword And Return Status  Dictionary Should Contain Key  ${current_record}  address

    # If address key not exists then add coords to dictionary with key address and add to object directly
    IF  ${is_address_key}
        Add Object To Json   ${current_record}   $..address    ${coords}
    ELSE 
        ${address}  Create Dictionary  address=${coords}
        Add Object To Json   ${current_record}  $   ${address}
    END

    Dictionary Should Contain Key  ${current_record}[address]  latitude
    Log To Console  \n${current_record}