Add to JSON
Add items into a JSON serializable object and return the result.
Arguments
Argument | Type | Default value | Description |
---|---|---|---|
doc | Dict[Hashable, str | int | float | bool | list | dict | None], List[str | int | float | bool | list | dict | None], str, int, float, bool, list, dict, None | null | JSON serializable object |
expr | str | null | JSONPath expression |
value | Dict[Hashable, str | int | float | bool | list | dict | None], List[str | int | float | bool | list | dict | None], str, int, float, bool, list, dict, None | null | values to either append or update |
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.
param doc: | JSON serializable object |
---|---|
param expr: | JSONPath expression |
param value: | values to either append or update |
return: | JSON serializable object of the updated JSON |
Robot Framework Example:
*** Task ***
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}
Python Example:
from RPA.JSON import JSON
# Change the name value for all people
js = JSON()
before = js.convert_string_to_json('{"People": [{"Name": "Mark"}, {"Name": "Jane"}]}')
person = {"Name": "John"}
after = js.add_to_json(before, "$.People", person)
print(after)
Convert JSON to String
Convert a JSON serializable object to a string and return it.
Arguments
Argument | Type | Default value | Description |
---|---|---|---|
doc | Dict[Hashable, str | int | float | bool | list | dict | None], List[str | int | float | bool | list | dict | None], str, int, float, bool, list, dict, None | null | JSON serializable object |
param doc: | JSON serializable object |
---|---|
return: | string of the JSON serializable object |
Robot Framework Example:
*** Task ***
Convert to string
${obj}= Create dictionary Key=Value
${json}= Convert JSON to string ${obj}
Should be equal ${json} {"Key": "Value"}
Python Example:
from RPA.JSON import JSON
from robot.libraries.BuiltIn import BuiltIn
obj = {"Key": "Value"}
json = JSON().convert_json_to_string(obj)
BuiltIn().should_be_equal(json, '{"Key": "Value"}')
Convert String to JSON
Convert a string to a JSON serializable object and return it.
Arguments
Argument | Type | Default value | Description |
---|---|---|---|
doc | str | null | JSON string |
param doc: | JSON string |
---|---|
return: | JSON serializable object of the string |
Robot Framework Example:
*** Task ***
Convert to json
${json}= Set variable {"Key": "Value"}
&{obj}= Convert string to JSON ${json}
Should be equal ${obj.Key} Value
Python Example:
from RPA.JSON import JSON
from robot.libraries.BuiltIn import BuiltIn
json = '{"Key": "Value"}'
obj = JSON().convert_string_to_json(json)
BuiltIn().should_be_equal(obj["Key"], "Value")
Delete from JSON
Delete values from a JSON serializable object and return the result. Will delete all values that match the expression.
Arguments
Argument | Type | Default value | Description |
---|---|---|---|
doc | Dict[Hashable, str | int | float | bool | list | dict | None], List[str | int | float | bool | list | dict | None], str, int, float, bool, list, dict, None | null | JSON serializable object or string |
expr | str | null | JSONPath expression |
param doc: | JSON serializable object or string |
---|---|
param expr: | JSONPath expression |
return: | JSON serializable object with values removed |
Examples
*** Task ***
Delete all people
&{before}= Convert string to JSON {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
&{after}= Delete from JSON ${before} $.People[*]
from RPA.JSON import JSON
# Delete all people
before = {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
after = JSON().delete_from_json(before, "$.People[*]")
print(after)
Get value from JSON
Get a single value from a JSON serializable object that matches the given expression.
Arguments
Argument | Type | Default value | Description |
---|---|---|---|
doc | Dict[Hashable, str | int | float | bool | list | dict | None], List[str | int | float | bool | list | dict | None], str, int, float, bool, list, dict, None | null | JSON serializable object or string |
expr | str | null | jsonpath expression |
default | Any, None | None | default value to return in the absence of a match |
Raises a ValueError if there is more than one match. Returns the given default argument (or None) if there were no matches.
param doc: | JSON serializable object or string |
---|---|
param expr: | jsonpath expression |
param default: | default value to return in the absence of a match |
return: | string containing the match OR default if there are no matches |
raises ValueError: | |
if more than one match is discovered |
Short Robot Framework Example:
*** Task ***
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
Short Python Example:
from RPA.JSON import JSON
# Get the name value for the second person.
people = {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
second = JSON().get_value_from_json(people, "$.People[1].Name")
print(second)
Extended Robot Framework Example:
*** Settings ***
Library RPA.JSON
Suite Setup Ingest JSON
*** Variables ***
${JSON_STRING} {
... "clients": [
... {
... "name": "Johnny Example",
... "email": "john@example.com",
... "orders": [
... {"address": "Streetroad 123", "state": "TX", "price": 103.20, "id":"guid-001"},
... {"address": "Streetroad 123", "state": "TX", "price": 98.99, "id":"guid-002"}
... ]
... },
... {
... "name": "Jane Example",
... "email": "jane@example.com",
... "orders": [
... {"address": "Waypath 321", "state": "WA", "price": 22.00, "id":"guid-003"},
... {"address": "Streetroad 123", "state": "TX", "price": 2330.01, "id":"guid-004"},
... {"address": "Waypath 321", "state": "WA", "price": 152.12, "id":"guid-005"}
... ]
... }
... ]
... }
${ID} guid-003
*** Tasks ***
Get email for specific order id
${email}= Get value from json ${JSON_DOC} $.clients[?(@..id=="${ID}")].email
Log \nOUTPUT IS\n ${email} console=${True}
Should be equal as strings ${email} jane@example.com
*** Keywords ***
Ingest JSON
${doc}= Convert string to json ${JSON_STRING}
Set suite variable ${JSON_DOC} ${doc}
Get values from JSON
Get all values from a JSON serializable object that match the given expression.
Arguments
Argument | Type | Default value | Description |
---|---|---|---|
doc | Dict[Hashable, str | int | float | bool | list | dict | None], List[str | int | float | bool | list | dict | None], str, int, float, bool, list, dict, None | null | JSON serializable object or string |
expr | str | null | JSONPath expression |
param doc: | JSON serializable object or string |
---|---|
param expr: | JSONPath expression |
return: | list of values that match |
Short Robot Framework Example:
*** Task ***
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
Short Python Example:
from RPA.JSON import JSON
# Get all the names for all people
people = {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
names = JSON().get_values_from_json(people, "$.People[*].Name")
print(second)
Extended Robot Framework Example:
*** Settings ***
Library RPA.JSON
Suite Setup Ingest JSON
*** Variables ***
${JSON_STRING} {
... "clients": [
... {
... "name": "Johnny Example",
... "email": "john@example.com",
... "orders": [
... {"address": "Streetroad 123", "state": "TX", "price": 103.20, "id":"guid-001"},
... {"address": "Streetroad 123", "state": "TX", "price": 98.99, "id":"guid-002"}
... ]
... },
... {
... "name": "Jane Example",
... "email": "jane@example.com",
... "orders": [
... {"address": "Waypath 321", "state": "WA", "price": 22.00, "id":"guid-003"},
... {"address": "Streetroad 123", "state": "TX", "price": 2330.01, "id":"guid-004"},
... {"address": "Waypath 321", "state": "WA", "price": 152.12, "id":"guid-005"}
... ]
... }
... ]
... }
${ID} guid-003
*** Tasks ***
Get All Prices and Order Ids
# Arithmetic operations only work when lists are of equal lengths and types.
${prices}= Get values from json
... ${JSON_DOC}
... $.clients[*].orders[*].id + " has price " + $.clients[*].orders[*].price.`str()`
Log \nOUTPUT IS\n ${prices} console=${True}
Should be equal as strings ${prices}
... ['guid-001 has price 103.2', 'guid-002 has price 98.99', 'guid-003 has price 22.0', 'guid-004 has price 2330.01', 'guid-005 has price 152.12']
Find Only Valid Emails With Regex
# The regex used in this example is simplistic and
# will not work with all email addresses
${emails}= Get values from json
... ${JSON_DOC}
... $.clients[?(@.email =~ "[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]+")].email
Log \nOUTPUT IS\n ${emails} console=${True}
Should be equal as strings ${emails} ['john@example.com', 'jane@example.com']
Find Orders From Texas Over 100
# The regex used in this example is simplistic and
# will not work with all email addresses
${orders}= Get values from json
... ${JSON_DOC}
... $.clients[*].orders[?(@.price > 100 & @.state == "TX")]
Log \nOUTPUT IS\n ${orders} console=${True}
Should be equal as strings ${orders}
... [{'address': 'Streetroad 123', 'state': 'TX', 'price': 103.2, 'id': 'guid-001'}, {'address': 'Streetroad 123', 'state': 'TX', 'price': 2330.01, 'id': 'guid-004'}]
*** Keywords ***
Ingest JSON
${doc}= Convert string to json ${JSON_STRING}
Set suite variable ${JSON_DOC} ${doc}
Load JSON from file
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.
Arguments
Argument | Type | Default value | Description |
---|---|---|---|
filename | str | null | path to input file |
encoding | utf-8 | file character encoding |
param filename: | path to input file |
---|---|
param encoding: | file character encoding |
return: | JSON serializable object of the JSON file |
Examples
*** Task ***
Load json
&{auth}= Load JSON from file auth.json
Log Current auth token: ${auth.token}
Save JSON to file
Save a JSON serializable object or a string containing a JSON value into a file.
Arguments
Argument | Type | Default value | Description |
---|---|---|---|
doc | Dict[Hashable, str | int | float | bool | list | dict | None], List[str | int | float | bool | list | dict | None], str, int, float, bool, list, dict, None | null | JSON serializable object or string |
filename | str | null | path to output file |
indent | int, None | None | if given this value is used for json file indent |
encoding | str | utf-8 | file character encoding |
param doc: | JSON serializable object or string |
---|---|
param filename: | path to output file |
param indent: | if given this value is used for json file indent |
param encoding: | file character encoding |
Robot Framework Example:
*** Tasks ***
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
Python Example:
from RPA.JSON import JSON
# Save dictionary to file.
john = {"name": "John", "mail": "john@example.com"}
JSON().save_json_to_file(john, "john.json")
Update value to JSON
Update existing values in a JSON serializable object and return the result. Will change all values that match the expression.
Arguments
Argument | Type | Default value | Description |
---|---|---|---|
doc | Dict[Hashable, str | int | float | bool | list | dict | None], List[str | int | float | bool | list | dict | None], str, int, float, bool, list, dict, None | null | JSON or string |
expr | str | null | JSONPath expression |
value | Dict[Hashable, str | int | float | bool | list | dict | None], List[str | int | float | bool | list | dict | None], str, int, float, bool, list, dict, None | null | New value for the matching item(s) |
param doc: | JSON or string |
---|---|
param expr: | JSONPath expression |
param value: | New value for the matching item(s) |
return: | JSON serializable object with updated results |
Short Robot Framework Example:
*** Tasks ***
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
from RPA.JSON import JSON
# Change the name key for all people
before = {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
after = JSON().update_value_to_json(before, "$.People[*].Name","JohnMalkovich")
print(after)
Extended Robot Framework Example:
*** Settings ***
Library RPA.JSON
Library Collections
Suite Setup Ingest JSON
*** Variables ***
${JSON_STRING} {
... "clients": [
... {
... "name": "Johnny Example",
... "email": "john@example.com",
... "id": "user-001",
... "orders": [
... {"address": "Streetroad 123", "state": "TX", "price": 103.20, "id":"guid-001"},
... {"address": "Streetroad 123", "state": "TX", "price": 98.99, "id":"guid-002"}
... ]
... },
... {
... "name": "Jane Example",
... "email": "jane@example.com",
... "id": "user-002",
... "orders": [
... {"address": "Waypath 321", "state": "WA", "price": 22.00, "id":"guid-003"},
... {"address": "Streetroad 123", "state": "TX", "price": 2330.01, "id":"guid-004"},
... {"address": "Waypath 321", "state": "WA", "price": 152.12, "id":"guid-005"}
... ]
... }
... ]
... }
${ID} guid-003
*** Tasks ***
Update user email
${updated_doc}= Update value to json
... ${JSON_DOC}
... $.clients[?(@.id=="user-001")].email
... johnny@example.com
Log \nNEW JSON IS\n ${updated_doc} console=${True}
${new_email}= Get value from json ${updated_doc} $.clients[?(@.id=="user-001")].email
Should be equal as strings ${new_email} johnny@example.com
Add additional charge to all prices in WA
# This example also shows how the update keyword changes the original JSON doc in memory.
${id_price}= Get values from json
... ${JSON_DOC}
... $.clients[*].orders[?(@.state=="WA")].id,price
FOR ${order_id} ${price} IN @{id_price}
Update value to json ${JSON_DOC} $.clients[*].orders[?(@.id=="${order_id}")].price ${{${price} * 1.06}}
END
Log \nNEW JSON IS\n ${JSON_DOC} console=${True}
${one_price}= Get value from json ${JSON_DOC} $..orders[?(@.id==${ID})].price
Should be equal as numbers ${one_price} 23.32
*** Keywords ***
Ingest JSON
${doc}= Convert string to json ${JSON_STRING}
Set suite variable ${JSON_DOC} ${doc}