简体   繁体   中英

edit a JSON file in Robot Framework

I want to add driver=1 to my sample_json.json file but can't figure out a way to write these changes permanently. This code saves the key-value to the object ${json_obj} but does not make any changes to the file sample_json.json

sample_json.json

{
    "Phones": {

        "debug": "on",

        "phone1": {
            "key":"value"            
        },

        "phone2": {
            "key":"value"
        }
    }
}

Robot file

*** Settings ***
Library    JSONLibrary

*** Variables ***
${SUBSCRIBER_A}    phone1

*** Test Cases ***
testcase 
   test    ${SUBSCRIBER_A}

*** Keywords ***
test
    [Arguments]    ${SUBSCRIBER_A}
    ${json_obj}=    Load JSON From File     sample_json.json
    ${object_to_add}=   Create Dictionary   driver=1
    ${json_obj}=    Add Object To Json    ${json_obj}    $..${SUBSCRIBER_A}    ${object_to_add}

Looks like you haven't fully understood how the library works. When you call Load JSON From File , the library will read the file, and return the data as a variable in memory (in your case, your ${json_obj} variable).

Now at this point, whenever you alter this data, you're only altering the data in memory, not the file itself.

You'll need to overwrite the file with your new data, which you can achieve using the Create File keyword. You'll likely need to convert your JSON dictionary to a string first, using the Convert JSON To String keyword.

Thanks for helping guys! Following is the code how it was done. I used the library operating system for writing the changes to the file but first used Convert JSON To String keyword on it.

*** Settings ***
Library    JSONLibrary
Library    OperatingSystem

*** Variables ***
${SUBSCRIBER_A}    phone1

*** Test Cases ***
testcase
   test    ${SUBSCRIBER_A}

*** Keywords ***
test
    [Arguments]    ${SUBSCRIBER_A}
    ${json_obj}=    Load JSON From File     example.json
    ${object_to_add}=   Create Dictionary   driver=1
    ${json_obj}=    Add Object To Json    ${json_obj}    $..${SUBSCRIBER_A}    ${object_to_add}
    ${new_obj}=    Convert JSON To String    ${json_obj}
    Create File    example.json    ${new_obj}    UTF-8

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