问题
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}
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/47283542/edit-a-json-file-in-robot-framework