├── .forceignore ├── .gitignore ├── LICENSE ├── README.md ├── force-app └── main │ └── default │ └── classes │ ├── JsonReader.cls │ ├── JsonReader.cls-meta.xml │ ├── JsonReaderTest.cls │ ├── JsonReaderTest.cls-meta.xml │ ├── RegexFindIterator.cls │ └── RegexFindIterator.cls-meta.xml └── sfdx-project.json /.forceignore: -------------------------------------------------------------------------------- 1 | # List files or directories below to ignore them when running force:source:push, force:source:pull, and force:source:status 2 | # More information: https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_exclude_source.htm 3 | # 4 | 5 | package.xml 6 | 7 | # LWC configuration files 8 | **/jsconfig.json 9 | **/.eslintrc.json 10 | 11 | # LWC Jest 12 | **/__tests__/** -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # This file is used for Git repositories to specify intentionally untracked files that Git should ignore. 2 | # If you are not using git, you can delete this file. For more information see: https://git-scm.com/docs/gitignore 3 | # For useful gitignore templates see: https://github.com/github/gitignore 4 | 5 | # Salesforce cache 6 | .sfdx/ 7 | .localdevserver/ 8 | 9 | # LWC VSCode autocomplete 10 | **/lwc/jsconfig.json 11 | 12 | # LWC Jest coverage reports 13 | coverage/ 14 | 15 | # Logs 16 | logs 17 | *.log 18 | npm-debug.log* 19 | yarn-debug.log* 20 | yarn-error.log* 21 | 22 | # Dependency directories 23 | node_modules/ 24 | 25 | # Eslint cache 26 | .eslintcache 27 | 28 | # MacOS system files 29 | .DS_Store 30 | 31 | # Windows system files 32 | Thumbs.db 33 | ehthumbs.db 34 | [Dd]esktop.ini 35 | $RECYCLE.BIN/ 36 | /config/JsonReader-scratch-def.json 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Nebula Consulting 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JSON Reader 2 | 3 | Read values from JSON by specifying simple paths like 'a.b' or 'a.b[2].c'. 4 | 5 | ## Examples 6 | 7 | Basic usage: 8 | 9 | String jsonString = '{"a": { "a2": "expected"} }'; 10 | 11 | Object result = new JsonReader(jsonString).read('a.a2'); 12 | 13 | System.assertEquals('expected', result); 14 | 15 | With lists: 16 | 17 | String jsonString = '{"a": { "a2": ["x", ["expected"]] } }'; 18 | 19 | Object result = new JsonReader(jsonString).read('a.a2[1][0]'); 20 | 21 | System.assertEquals('expected', result); 22 | 23 | Specifying behaviour for missing keys: 24 | 25 | String jsonString = '{"a": { "a2": "expected"} }'; 26 | final String NO_RESULT = 'no result'; 27 | 28 | Object result = new JsonReader(jsonString) 29 | .setMissingKeyResult(NO_RESULT) 30 | .read('a.nope'); 31 | 32 | System.assertEquals(NO_RESULT, result); 33 | 34 | ## License 35 | 36 | MIT, see [LICENSE](LICENSE) 37 | 38 | -------------------------------------------------------------------------------- /force-app/main/default/classes/JsonReader.cls: -------------------------------------------------------------------------------- 1 | /** 2 | * @author aidan@nebulaconsulting.co.uk 3 | * @date 19/06/2020 4 | * @description Read keys from a JSON object by specifying the path. Suitable for only a small number of reads as 5 | * each one is found independently 6 | */ 7 | 8 | public class JsonReader { 9 | 10 | private Object theData; 11 | private Object missingKeyResult = null; 12 | 13 | private static final Pattern JSON_SEARCH_PATH_PATTERN = Pattern.compile('(\\[\\d+])|([\\w]+)'); 14 | 15 | public JsonReader(String jsonString) { 16 | theData = JSON.deserializeUntyped(jsonString); 17 | } 18 | 19 | public JsonReader(Object untypedJsonObject) { 20 | theData = untypedJsonObject; 21 | } 22 | 23 | public JsonReader setMissingKeyResult(Object missingKeyResult) { 24 | this.missingKeyResult = missingKeyResult; 25 | return this; 26 | } 27 | 28 | public Object read(String jsonPath) { 29 | return read(new RegexFindIterator(JSON_SEARCH_PATH_PATTERN, jsonPath), theData); 30 | } 31 | 32 | private Object read(RegexFindIterator jsonPathIterator, Object thisData) { 33 | String thisKey = jsonPathIterator.next(); 34 | 35 | Object nextData = thisKey.contains('[') ? 36 | readFromList((List)thisData, thisKey) 37 | : 38 | readFromMap((Map)thisData, thisKey); 39 | 40 | if(nextData != null && nextData != missingKeyResult && jsonPathIterator.hasNext()) { 41 | return read(jsonPathIterator, nextData); 42 | } else { 43 | return nextData; 44 | } 45 | } 46 | 47 | private Object readFromMap(Map dataAsMap, String thisKey) { 48 | return dataAsMap.containsKey(thisKey) ? dataAsMap.get(thisKey) : missingKeyResult; 49 | } 50 | 51 | private Object readFromList(List dataAsList, String thisKey) { 52 | Integer index = Integer.valueOf(thisKey.substring(1, thisKey.length() - 1)); 53 | if (index < dataAsList.size()) { 54 | return dataAsList[index]; 55 | } else { 56 | return missingKeyResult; 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /force-app/main/default/classes/JsonReader.cls-meta.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 48.0 4 | Active 5 | 6 | -------------------------------------------------------------------------------- /force-app/main/default/classes/JsonReaderTest.cls: -------------------------------------------------------------------------------- 1 | /** 2 | * @author aidan@nebulaconsulting.co.uk 3 | * @date 19/06/2020 4 | */ 5 | 6 | @IsTest 7 | private class JsonReaderTest { 8 | 9 | @IsTest 10 | static void singleKey() { 11 | String jsonString = '{"a": "expected"}'; 12 | 13 | Test.startTest(); 14 | Object result = new JsonReader(jsonString).read('a'); 15 | Test.stopTest(); 16 | 17 | System.assertEquals('expected', result); 18 | } 19 | 20 | @IsTest 21 | static void nestedKey() { 22 | String jsonString = '{"a": { "a2": "expected"} }'; 23 | 24 | Test.startTest(); 25 | Object result = new JsonReader(jsonString).read('a.a2'); 26 | Test.stopTest(); 27 | 28 | System.assertEquals('expected', result); 29 | } 30 | 31 | @IsTest 32 | static void withList() { 33 | String jsonString = '{"a": { "a2": ["x", "expected"] } }'; 34 | 35 | Test.startTest(); 36 | Object result = new JsonReader(jsonString).read('a.a2[1]'); 37 | Test.stopTest(); 38 | 39 | System.assertEquals('expected', result); 40 | } 41 | 42 | @IsTest 43 | static void twoDimensionalList() { 44 | String jsonString = '{"a": { "a2": ["x", ["expected"]] } }'; 45 | 46 | Test.startTest(); 47 | Object result = new JsonReader(jsonString).read('a.a2[1][0]'); 48 | Test.stopTest(); 49 | 50 | System.assertEquals('expected', result); 51 | } 52 | 53 | @IsTest 54 | static void mixedListsAndNesting() { 55 | String jsonString = '{"a": { "a2": ["x", { "b": [["expected"]] } ] } }'; 56 | 57 | Test.startTest(); 58 | Object result = new JsonReader(jsonString).read('a.a2[1].b[0][0]'); 59 | Test.stopTest(); 60 | 61 | System.assertEquals('expected', result); 62 | } 63 | 64 | @IsTest 65 | static void missingKey() { 66 | String jsonString = '{"a": { "a2": "expected"} }'; 67 | final String NO_RESULT = 'no result'; 68 | Test.startTest(); 69 | Object result = new JsonReader(jsonString) 70 | .setMissingKeyResult(NO_RESULT) 71 | .read('a.nope'); 72 | Test.stopTest(); 73 | 74 | System.assertEquals(NO_RESULT, result); 75 | } 76 | } -------------------------------------------------------------------------------- /force-app/main/default/classes/JsonReaderTest.cls-meta.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 48.0 4 | Active 5 | 6 | -------------------------------------------------------------------------------- /force-app/main/default/classes/RegexFindIterator.cls: -------------------------------------------------------------------------------- 1 | /** 2 | * @author aidan@nebulaconsulting.co.uk 3 | * @date 19/06/2020 4 | * @description Repeatedly calls Matcher.find(), returning the whole matching result (i.e. Matcher.group()) via 5 | * an Iterator interface. Note: does not iterate the groups within each find 6 | */ 7 | 8 | global class RegexFindIterator implements Iterator { 9 | 10 | private Matcher matcher; 11 | private Boolean hasNext; 12 | 13 | public RegexFindIterator(Pattern pattern, String searchString) { 14 | matcher = pattern.matcher(searchString); 15 | hasNext = matcher.find(); 16 | } 17 | 18 | public Boolean hasNext() { 19 | return hasNext; 20 | } 21 | 22 | public String next() { 23 | String result = matcher.group(); 24 | hasNext = matcher.find(); 25 | return result; 26 | } 27 | } -------------------------------------------------------------------------------- /force-app/main/default/classes/RegexFindIterator.cls-meta.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 48.0 4 | Active 5 | 6 | -------------------------------------------------------------------------------- /sfdx-project.json: -------------------------------------------------------------------------------- 1 | { 2 | "packageDirectories": [ 3 | { 4 | "path": "force-app", 5 | "default": true 6 | } 7 | ], 8 | "namespace": "", 9 | "sfdcLoginUrl": "https://login.salesforce.com", 10 | "sourceApiVersion": "48.0" 11 | } --------------------------------------------------------------------------------