Python API

JSON

class RPA.JSON.JSON

Bases: object

JSON is a library for manipulating JSON files and strings.

JSON is a common data interchange format inspired by a subset of the Javascript programming language, but these days is a de facto standard in modern web APIs and is language agnostic.

Serialization

The term serialization refers to the process of converting Robot Framework or Python types to JSON or the other way around.

Basic types can be easily converted between the domains, and the mapping is as follows:

JSON

Python

object

dict

array

list

string

str

number (int)

int

number (real)

float

true

True

false

False

null

None

About JSONPath

Reading and writing values from/to JSON serializable objects is done using JSONPath. It’s a syntax designed to quickly and easily refer to specific elements in a JSON structure.

Compared to Python’s normal dictionary access, JSONPath expressions can target multiple elements through features such as conditionals and wildcards, which can simplify many JSON-related operations. It’s analogous to XPath for XML structures.

Syntax example

For this example consider the following structure:

{
  "clients": [
    {
      "name": "Johnny Example",
      "email": "john@example.com",
      "orders": [
          {"address": "Streetroad 123", "price": 103.20},
          {"address": "Streetroad 123", "price": 98.99}
      ]
    },
    {
      "name": "Jane Example",
      "email": "jane@example.com",
      "orders": [
          {"address": "Waypath 321", "price": 22.00},
          {"address": "Streetroad 123", "price": 2330.01}
      ]
    }
  ]
}

In the simplest case JSONPath can replace nested access:

# First order of first client, with direct dictionary access
${value}=    Set variable    ${json}["clients"][0]["orders"][0]

# JSONPath access
${value}=    Get value from JSON    ${json}    $.clients[0].orders[0]

But the power comes from complicated expressions:

# Find delivery addresses for all orders
${prices}=        Get values from JSON    $..address

# Find orders that cost over 100
${expensives}=    Get values from JSON    $..orders[?(@.price>100)]

Supported Expressions

The supported syntax elements are:

Element

Description

$

Root object/element

@

Current object/element

. or []

Child operator

..

Recursive descent

*

Wilcard, any element

[n]

Array index

[a:b:c]

Array slice (start, end, step)

[a,b]

Union of indices or names

?()

Apply a filter expression

()

Script expression

There are a multitude of different script expressions in addition to the elements listed above, which can be seen in the aforementioned article.

For further library usage examples, see the individual keywords.

ROBOT_LIBRARY_DOC_FORMAT = 'REST'
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
add_to_json(doc: Union[Dict[str, Any], List[Any], str, int, float, bool, None], expr: str, value: Union[Dict[str, Any], List[Any], str, int, float, bool, None])

Add items into a JSON serializable object and return the result.

If the target is a list, the values are appended to the end. If the target is a dict, the keys are either added or updated.

Parameters
  • doc – JSON serializable object

  • expr – JSONPath expression

  • value – values to either append or update

Example:

# Change the name value for all people
&{before}=    Convert string to JSON   {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
&{person}=    Create dictionary      Name=John
&{after}=     Add to JSON    ${before}   $.People    ${person}
convert_json_to_string(doc: Union[Dict[str, Any], List[Any], str, int, float, bool, None]) → str

Convert a JSON serializable object to a string and return it.

Parameters

doc – JSON serializable object

Example:

${obj}=    Create dictionary    Key=Value
${json}=   Convert JSON to string    ${obj}
Should be equal    ${json}     {"Key": "Value"}
convert_string_to_json(doc: str) → Union[Dict[str, Any], List[Any], str, int, float, bool, None]

Convert a string to a JSON serializable object and return it.

Parameters

doc – JSON string

Example:

${json}=    Set variable    {"Key": "Value"}
&{obj}=     Convert string to JSON    ${json}
Should be equal    ${obj.Key}    Value
delete_from_json(doc: Union[Dict[str, Any], List[Any], str, int, float, bool, None], expr: str)

Delete values from a JSON serializable object and return the result. Will delete all values that match the expression.

Parameters
  • doc – JSON serializable object or string

  • expr – JSONPath expression

Example:

# Delete all people
&{before}=    Convert string to JSON   {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
&{after}=     Delete from JSON    ${before}   $.People[*]
get_value_from_json(doc: Union[Dict[str, Any], List[Any], str, int, float, bool, None], expr: str, default: Any = None)

Get a single value from a JSON serializable object that matches the given expression.

Raises a ValueError if there is more than one match. Returns the given default argument (or None) if there were no matches.

Parameters
  • doc – JSON serializable object or string

  • expr – jsonpath expression

Example:

# Get the name value for the first person
&{people}=    Convert string to JSON   {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
${first}=     Get value from JSON      ${people}   $.People[0].Name
get_values_from_json(doc: Union[Dict[str, Any], List[Any], str, int, float, bool, None], expr: str)

Get all values from a JSON serializable object that match the given expression.

Parameters
  • doc – JSON serializable object or string

  • expr – JSONPath expression

Example:

# Get all the names for all people
&{people}=    Convert string to JSON   {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
@{names}=     Get values from JSON     ${people}   $.People[*].Name
load_json_from_file(filename: str, encoding='utf-8') → Union[Dict[str, Any], List[Any], str, int, float, bool, None]

Load JSON data from a file, and return it as JSON serializable object. Depending on the input file the object can be either a dictionary, a list, or a scalar value.

Parameters
  • filename – path to input file

  • encoding – file character encoding

Example:

&{auth}=    Load JSON from file    auth.json
Log   Current auth token: ${auth.token}
save_json_to_file(doc: Union[Dict[str, Any], List[Any], str, int, float, bool, None], filename: str, indent: int = None, encoding='utf-8')

Save a JSON serializable object or a string containg a JSON value into a file.

Parameters
  • doc – JSON serializable object or string

  • filename – path to output file

  • indent – if given this value is used for json file indent

  • encoding – file character encoding

Example:

# Save dictionary to file
${john}=    Create dictionary    name=John    mail=john@example.com
Save JSON to file    ${john}    john.json

# Save string to file
${mark}=    Set variable    {"name": "Mark", "mail": "mark@example.com"}
Save JSON to file    ${mark}    mark.json
update_value_to_json(doc: Union[Dict[str, Any], List[Any], str, int, float, bool, None], expr: str, value: Union[Dict[str, Any], List[Any], str, int, float, bool, None])

Update existing values in a JSON serializable object and return the result. Will change all values that match the expression.

Parameters
  • doc – JSON or string

  • expr – JSONPath expression

  • value – New value for the matching item(s)

Example:

# Change the name key for all people
&{before}=    Convert string to JSON   {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
&{after}=     Update value to JSON     ${before}   $.People[*].Name    JohnMalkovich