|
| 1 | +Parse JSON with GlideJsonPath |
| 2 | +This script demonstrates how to use the GlideJsonPath API in ServiceNow to parse a complex JSON string and extract specific data. In this example, it efficiently retrieves an array of player names from a nested JSON structure representing cricket team information. |
| 3 | +Overview |
| 4 | +The script performs the following actions: |
| 5 | +Initializes GlideJsonPath: A new instance of GlideJsonPath is created, passing the target JSON string as a parameter. |
| 6 | +Reads data with JSONPath: The read() method is called with a JSONPath expression to extract the desired data. The expression "$['lib']['jsonpath']['cricket']['players'][*]" navigates to the array of players: |
| 7 | +$ represents the root of the JSON object. |
| 8 | +['lib'], ['jsonpath'], and ['cricket'] use bracket notation to traverse the nested object structure. |
| 9 | +['players'] accesses the array of player names. |
| 10 | +[*] is a wildcard that returns all elements in the players array. |
| 11 | +Stores the result: The extracted array of player names is stored in the l variable. |
| 12 | +Use case |
| 13 | +This script is useful in scenarios where you need to parse JSON data returned from a REST API call or an integration. By using GlideJsonPath, you can quickly and efficiently extract specific pieces of information without writing complex code to traverse the entire JSON object manually. |
| 14 | +How to use |
| 15 | +This script is intended for use in a server-side context within ServiceNow, such as a Script Include or Business Rule. |
| 16 | +Example: Script Include |
| 17 | +javascript |
| 18 | +var CricketJsonParser = Class.create(); |
| 19 | +CricketJsonParser.prototype = { |
| 20 | + initialize: function() { |
| 21 | + }, |
| 22 | + |
| 23 | + getPlayers: function() { |
| 24 | + var jsonString = '{"lib":{"jsonpath":{"cricket":{"name":"India","players":["Rohit","Dhoni","Kholi"]}}}}'; |
| 25 | + var v = new GlideJsonPath(jsonString); |
| 26 | + var playerNames = v.read("$['lib']['jsonpath']['cricket']['players'][*]"); |
| 27 | + |
| 28 | + // At this point, `playerNames` is a JavaObject array. |
| 29 | + // You can log it or process it further. |
| 30 | + gs.info("Extracted players: " + JSON.stringify(playerNames)); |
| 31 | + |
| 32 | + return playerNames; |
| 33 | + }, |
| 34 | + |
| 35 | + type: 'CricketJsonParser' |
| 36 | +}; |
| 37 | +Use code with caution. |
| 38 | + |
| 39 | +Customization |
| 40 | +JSON Data: Replace the hardcoded jsonString with the variable that holds your JSON data (e.g., the body of a REST response). |
| 41 | +JSONPath Expression: Modify the JSONPath expression in the read() method to extract different data from your JSON structure. |
| 42 | +Result Handling: The read() function returns a JavaObject array, not a standard JavaScript array. If you need to use JavaScript array methods (like forEach), you may need to convert it. |
0 commit comments