ROBOT 中的 Json 处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35262216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:16:30  来源:igfitidea点击:

Json handling in ROBOT

jsonrobotframework

提问by Vidya S

I have a Json file in which there is a field which I need to edit and save the file for next usage.

我有一个 Json 文件,其中有一个字段,我需要编辑并保存该文件以备下次使用。

But the field which I need to edit is as shown below,

但是我需要编辑的字段如下所示,

The value I need to assign fr the field is generated Randomly in run time which i'll be capturing in a variable and pass it to this json specific key "dp" then save the json.

我需要分配给 fr 字段的值是在运行时随机生成的,我将在一个变量中捕获它并将其传递给这个 json 特定键“dp”,然后保存 json。

The saved json will be used for REST POST url.

保存的 json 将用于 REST POST url。

            {
                "p": "10",
                "v": 100,
                "vt": [
                    {
                        "dp": "Field to be edited"(integer value) , 
                  ]          
            }

回答by Bryan Oakley

The simplest solution would be to write a python keyword that can change the value for you. However, you can solve this with robot keywords by performing the following steps:

最简单的解决方案是编写一个可以为您更改值的 python 关键字。但是,您可以通过执行以下步骤使用机器人关键字解决此问题:

  1. convert the JSON string to a dictionary
  2. modify the dictionary
  3. convert the dictionary back to a JSON string
  1. 将 JSON 字符串转换为字典
  2. 修改字典
  3. 将字典转换回 JSON 字符串

Convert the JSON string to a dictionary

将 JSON 字符串转换为字典

Python has a module (json) for working with JSON data. You can use the evaluatekeyword to convert your JSON string to a python dictionary using the loads(load string) method of that module.

Python 有一个模块 ( json) 用于处理 JSON 数据。您可以使用该模块的加载(加载字符串)方法,使用evaluate关键字将您的JSON 字符串转换为python 字典。

Assuming your JSON data is in a robot variable named ${json_string}, you can convert it to a python dictionary like this:

假设您的 JSON 数据位于名为 的机器人变量中${json_string},您可以将其转换为 Python 字典,如下所示:

${json}=    evaluate    json.loads('''${json_string}''')    json

With the above, ${json}now holds a reference to a dictionary that contains all of the json data.

有了上面的,${json}现在持有对包含所有 json 数据的字典的引用。

Modify the dictionary

修改字典

The Collectionslibrary that comes with robot has a keyword named set to dictionarywhich can be used to set the value of a dictionary element. In this case, you need to change the value of a dictionary nested inside the vtelement of the JSON object. We can reference that nested dictionary using robot's extended variable syntax.

robots自带的Collections库有一个关键字set to dictionary,可以用来设置字典元素的值。在这种情况下,您需要更改嵌套在vtJSON 对象元素内的字典的值。我们可以使用机器人的扩展变量语法引用该嵌套字典。

For example:

例如:

set to dictionary    ${json["vt"]}    dp=the new value

With that, ${json}now has the new value. However, it is still a python dictionary rather than JSON data, so there's one more step.

有了这个, ${json}现在有了新的价值。但是,它仍然是一个 python 字典而不是 JSON 数据,所以还有一个步骤。

Convert the dictionary back to JSON

将字典转换回 JSON

Converting the dictionary back to JSON is the reverse of the first step. Namely, use the dumps(dump string) method of the json module:

将字典转换回 JSON 是第一步的逆过程。即使用json模块的dumps(dump string)方法:

${json_string}=    evaluate    json.dumps(${json})    json

With that, ${json_string}will contain a valid JSON string with the modified data.

这样,${json_string}将包含带有修改数据的有效 JSON 字符串。



Complete example

完整示例

The following is a complete working example. The JSON string will be printed before and after the substitution of the new value:

下面是一个完整的工作示例。JSON 字符串将在替换新值之前和之后打印:

*** Settings ***
Library    Collections

*** Test Cases ***
Example
    ${json_string}=    catenate
    ...  {
    ...    "p": "10",
    ...    "v": 100,
    ...    "vt": {
    ...            "dp": "Field to be edited"
    ...          }
    ...  }

    log to console       \nOriginal JSON:\n${json_string}
    ${json}=             evaluate        json.loads('''${json_string}''')    json
    set to dictionary    ${json["vt"]}    dp=the new value
    ${json_string}=      evaluate        json.dumps(${json})                 json
    log to console       \nNew JSON string:\n${json_string}

回答by idomoni

For reading and writing data to and from file I am using OperatingSystem library

为了从文件读取和写入数据,我使用了操作系统库

${json} Get Binary File ${json_path}nameOfJsonFile.json

It works for me on API testing, to read .json and POST, like here

它适用于我的 API 测试,读取 .json 和 POST,就像这里

*** Settings ***
Library    Collections
Library    ExtendedRequestsLibrary 
Library    OperatingSystem
*** Variables ***  
${uri}    https://blabla.com/service/
${json_path}    C:/home/user/project/src/json/
*** Test Cases ***
Robot Test Case  
   Create Session    alias    ${uri}    
   &{headers}  Create Dictionary  Content-Type=application/json; charset=utf-8
   ${json}  Get Binary File  ${json_path}nameOfJsonFile.json
   ${resp}    Post Request    alias    data=${json}    headers=${headers}
   Should Be Equal As Strings    ${resp.status_code}    200

回答by codemech

For integer values in JSON, the other answers did not work for me. This worked:

对于 JSON 中的整数值,其他答案对我不起作用。这有效:

${json}=    Catenate    {    "p": "10",    "v": 100,    "vt": {    "dp": "Field to be edited"   }    }
${value}    Set Variable    2    #the value you want
${value}    Convert To Integer    ${value}
${json}=    Evaluate    json.loads('''${json}''')    json
Set To Dictionary    ${json["vt"]}    dp=${value}
${json}=    Evaluate    json.dumps(${json})    json
Log    ${json}

Convert To Integer was required, otherwise the value is still in string "${value}"

需要转换为整数,否则该值仍在字符串“${value}”中