Skip to content

How do I replace existing keys in the JSON object by path

This example demonstrates replacing existing keys in the JSON object by path.

In the solution shown below, store the JSON object, JSON path and new key into separate variables using "store" command. The existing key is replaced with a new key at the specified path within the JSON object using "jsonReplaceKeysByPaths" command. The result is stored into another variable.

Solution:

# Command Target Value
Store the JSON object in a variable
1 store {"age":45,"income":25000,"zipcodes":[{"zipcode":90001,"state": "California"}]} JSON
Store the JSON path in a variable
2 store
$.zipcodes
JSONPath
Storing the new key to be replaced in the JSON object
3 store
zipcodeDetails Value
Replacing the existing key for the defined path in the JSON object with new key and storing the result in a variable
4 jsonReplaceKeysByPaths
${JSON}||{${JSONPath},${Value}} Final_JSON

Tips, Tricks, Gotchas & Best Practices:  

  • You can also replace multiple keys by providing multiple {path, value} combinations separated by "||" symbol.
  • You can call the JSON, JSON path and value directly in the "Target" field separated by "||" symbol in "jsonReplaceKeysByPaths" command instead of storing them into a variable.
  • As a best practice, it is always advisable to define the variable names without any spaces and if you want to differentiate the words, use underscores.


Feedback and Knowledge Base