JSON manipulation
When working with APIs, JSON is one of the most popular data formats.
The RPA.JSON
library allows converting, reading, writing, manipulating, saving, and loading JSON using JSONPath.
Robot Framework example
*** Settings ***
Documentation Examples of JSON operations.
Library RPA.JSON
*** Tasks ***
JSON operations
${json}= Convert String to JSON {"orders": [{"id": 1},{"id": 2}]}
# ${json} = {'orders': [{'id': 1}, {'id': 2}]}
${first_order_id}= Get value from JSON ${json} $.orders[0].id
# ${first_order_id} = 1
${all_ids}= Get values from JSON ${json} $..id
# ${all_ids} = [1, 2]
${json}= Add to JSON ${json} $.orders {"id": 3}
# ${json} = {'orders': [{'id': 1}, {'id': 2}, '{"id": 3}']}
${json}= Delete from JSON ${json} $.orders[-1:]
# ${json} = {'orders': [{'id': 1}, {'id': 2}]}
${json}= Update value to JSON ${json} $.orders[1].id 4
# ${json} = {'orders': [{'id': 1}, {'id': '4'}]}
${json_as_string}= Convert JSON to String ${json}
# ${json_as_string} = {"orders": [{"id": 1}, {"id": "4"}]}
Save JSON to file ${json_as_string} orders.json
${json}= Load JSON from file orders.json
# ${json} = {'orders': [{'id': 1}, {'id': '4'}]}
Python example
Disclaimer: The standard Python
json
library can handle JSON manipulation very effectively. If going 100% Python, consider using that. You do not have to useRPA.JSON
library in that case! The example here is to provide comparison of using the library in Robot Framework and in Python.
from RPA.JSON import JSON
json_lib = JSON()
def json_operations():
json = json_lib.convert_string_to_json('{"orders": [{"id": 1},{"id": 2}]}')
first_order_id = json_lib.get_value_from_json(json, "$.orders[0].id")
all_ids = json_lib.get_values_from_json(json, "$..id")
json = json_lib.add_to_json(json, "$.orders", {"id": 3})
json = json_lib.delete_from_json(json, "$.orders[-1:]")
json = json_lib.update_value_to_json(json, "$.orders[1].id", 4)
json_as_string = json_lib.convert_json_to_string(json)
json_lib.save_json_to_file(json_as_string, "orders.json")
json = json_lib.load_json_from_file("orders.json")
def main():
json_operations()
if __name__ == "__main__":
main()
Last edit: May 5, 2022