- Notifications
You must be signed in to change notification settings - Fork0
A minimum implementation of JSON Path in Apex.
License
Dogeforce/apex-json-path
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This repository contains a minimum implementation of theJSON Path Syntax. With this you can access data from a JSON string using a path specified by another string.
Might come in handy with integrations, specially, where one might have to read data from a JSON payload according to some specifications from data or metadata instead of deserializing the whole thing to an Apex type.
To get an attribute value:
JSONPathj=newJSONPath('{"name":"John","company":{"name":"Company"}}');StringcompanyName=j.get('$.company.name');System.assertEquals('Company',companyName,'Wrong company name.');
It works for returning entire objects. So you could use$.company to get theObject that contains the company data (then you could cast it to aMap<String, Object> and access thename from there if you wanted to). This is also true for returning inner lists.
JSONPathjpListNested=newJSONPath('[{"attr":[{"name":"John"},{"name":"Mary"}]}]');System.assertEquals('Mary',jpListNested.get('$[0].attr[1].name'),'Incorrect data.');
Also works for returning specific attributes from inner lists. So if the JSON payload is a list or the object contains a list then it is reachable using the[] or[*] syntax:
JSONPathjpAttributeListFromObjectList=newJSONPath('[{"name":"John"},{"name":"Mary"}]');List<Object>names= (List<Object>)jpAttributeListFromObjectList.get('$[*].name');// names[0] = John and names[1] = 'Mary'JSONPathjpAttributeListFromInnerObjectList=newJSONPath('{"people":[{"name":"John"},{"name":"Mary"}]}}');names= (List<Object>)jpAttributeListFromInnerObjectList.get('$.people[*].name');// names[0] = John and names[1] = 'Mary'
The following functions are available for usage with list attributes:
minto get the minimum value (returns a double);maxto get the maximum value (returns a double);avgto get the average value (returns a double);sumto get the sum of values (returns a double);sizeandlengthto get the quantity of values in the list (returns an integer);emptyto get a boolean indicating if the list is empty;
Usage:
JSONPatharrayFunctions=newJSONPath('{"numbers":[1, 2, 3, 40]}');arrayFunctions.get('$.numbers.empty()');// falsearrayFunctions.get('$.numbers.length()');// 4arrayFunctions.get('$.numbers.size()');// 4arrayFunctions.get('$.numbers.min()');// 1arrayFunctions.get('$.numbers.max()');// 40arrayFunctions.get('$.numbers.avg()');// 11.5
About
A minimum implementation of JSON Path in Apex.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.