Skip to content

Instantly share code, notes, and snippets.

@gbroques
Last active July 17, 2023 21:06
Show Gist options
  • Save gbroques/5eaaa3736e85882dfb562fa839a109b1 to your computer and use it in GitHub Desktop.
Save gbroques/5eaaa3736e85882dfb562fa839a109b1 to your computer and use it in GitHub Desktop.
getJsonPropertyExpressions
/**
* 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