Last active
July 17, 2023 21:06
-
-
Save gbroques/5eaaa3736e85882dfb562fa839a109b1 to your computer and use it in GitHub Desktop.
getJsonPropertyExpressions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get an array of all possible JSON path expressions for an object. | |
* | |
* @example | |
* getJsonPathExpressions({ | |
* "firstName": "John", | |
* "address": { "city": "Nara" }, | |
* "phoneNumbers": [ { "type": "iPhone", "number": "0123-4567-8888" } ] | |
* }) | |
* // => ["$.firstName", "$.address.city", "$.phoneNumbers[*].type", "$.phoneNumbers[*].number"] | |
*/ | |
function getJsonPathExpressions(obj, expressions = [], propertyPath = "$") { | |
if (typeof obj === "object" && !Array.isArray(obj)) { | |
Object.entries(obj).forEach(([key, value]) => { | |
const jsonPath = propertyPath + "." + key; | |
if (value !== null && typeof value === "object") { | |
getJsonPathExpressions(value, expressions, jsonPath); | |
} else { | |
expressions.push(jsonPath); | |
} | |
}); | |
} else { // obj is an array | |
const jsonPath = propertyPath + "[*]"; | |
if (obj.length) { | |
const firstElement = obj[0]; | |
if (firstElement !== null && typeof firstElement === "object") { | |
getJsonPathExpressions(firstElement, expressions, jsonPath); | |
} else { | |
expressions.push(jsonPath); | |
} | |
} else { | |
expressions.push(jsonPath); | |
console.warn(`Empty array for path ${propertyPath}.`); | |
} | |
} | |
return expressions; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment