jsonpath
jsonpath copied to clipboard
Square brackets & double quotes in keys
Goal
I have an input json like this ⬇️ and I want the pathExpression
of the key whose value is tenth
.
{
"name": "my integration",
"settings": {
"id": "first",
"name": "second",
"age": "third",
"a.b": "fourth",
"a": {
"b": "fifth"
},
"6nine": "sixth",
".": "seventh",
"10": "eighth",
"[square with space]": "ninth",
"double \"quote\" with space": "tenth",
"[square] and \"double\" quote with space ": "eleventh",
"[\"quote inside square\"]": "twelfth"
}
}
Attempt 1
jp.value(o, '$["settings"]["double \"quote\" with space"]')
Threw the follwing error:
Uncaught Error: Parse error on line 1:
...settings"]["double "quote" with space"]
-----------------------^
Expecting ']', ',', got 'IDENTIFIER'
at Parser.parseError (/Users/sachin/io/integrator/node_modules/jsonpath/generated/parser.js:166:15)
at Parser.parser.yy.parseError (/Users/sachin/io/integrator/node_modules/jsonpath/lib/parser.js:13:17)
at Parser.parse (/Users/sachin/io/integrator/node_modules/jsonpath/generated/parser.js:224:22)
at JSONPath._normalize (/Users/sachin/io/integrator/node_modules/jsonpath/lib/index.js:198:24)
at JSONPath.stringify (/Users/sachin/io/integrator/node_modules/jsonpath/lib/index.js:168:15)
at JSONPath.value (/Users/sachin/io/integrator/node_modules/jsonpath/lib/index.js:63:31)
Attempt 2
jp.value(o, "$['settings']['double \"quote\" with space']")
Returned
undefined
Attempt 3
I generated the pathExpression
like this:
jp.paths(o, '$..*')
/** Prints this:
[
[ '$', 'name' ],
[ '$', 'settings' ],
[ '$', 'arr' ],
[ '$', 'settings', '10' ],
[ '$', 'settings', 'id' ],
[ '$', 'settings', 'name' ],
[ '$', 'settings', 'age' ],
[ '$', 'settings', 'a.b' ],
[ '$', 'settings', 'a' ],
[ '$', 'settings', '6nine' ],
[ '$', 'settings', '.' ],
[ '$', 'settings', '[square with space]' ],
[ '$', 'settings', 'double "quote" with space' ], <------------------------ path of interest
[ '$', 'settings', '[square] and "double" quote with space ' ],
[ '$', 'settings', '["quote inside square"]' ],
[ '$', 'settings', 'a', 'b' ],
[ '$', 'arr', 0 ],
[ '$', 'arr', 1 ]
]
*/
jp.stringify(o, [ '$', 'settings', 'double "quote" with space' ])
/** Prints this:
'$.settings["double \\"quote\\" with space"]' <-------------------------- required path expression (we achieved our goal)
*/
But wait.. If this path expression corresponds to the node with value tenth
, then the below expression should output tenth
:
jp.value(o, '$.settings["double \\"quote\\" with space"]')
/**
prints undefined
*/
From attempt 3, it seems to me that there is a limitation when square brackets or double quotes are involved in keys. If that is not the case, any help is appreciated.