Hayley Hayley - 1 month ago 14
JSON Question

JSONPath Syntax when dot in key

Please forgive me if I use the incorrect terminology, I am quite the novice.

I have some simple JSON:

{
"properties": {
"footer.navigationLinks": {
"group": "layout"
, "default": [
{
"text": "Link a"
, "href": "#"
}
]
}
}


I am trying to pinpoint "footer.navigationLinks" but I am having trouble with the dot in the key name. I am using http://jsonpath.com/ and when I enter

$.properties['footer.navigationLinks']


I get 'No match'. If I change the key to "footernavigationLinks" it works but I cannot control the key names in the JSON file.

Please can someone help me target that key name?

Answer

This issue was reported in 2007 as issue #4 - Member names containing dot fail and fixed.

The fix is not present in this online jsonpath.com implementation, but it is fixed in this old archive and probably in most of the forks that have been created since (like here and here).

Details about the bug

A comparison between the buggy and 2007-corrected version of the code, reveals that the correction was made in the private normalize function.

In the 2007-corrected version it reads:

normalize: function(expr) {
    var subx = [];
    return expr.replace(/[\['](\??\(.*?\))[\]']|\['(.*?)'\]/g, function($0,$1,$2){
        return "[#"+(subx.push($1||$2)-1)+"]";
    })  /* http://code.google.com/p/jsonpath/issues/detail?id=4 */
    .replace(/'?\.'?|\['?/g, ";")
    .replace(/;;;|;;/g, ";..;")
    .replace(/;$|'?\]|'$/g, "")
    .replace(/#([0-9]+)/g, function($0,$1){
         return subx[$1];
    });
},

The first and last replace in that sequence make sure the second replace does not interpret a point in a property name as a property separator.

I had a look at the more up-to-date forks that have been made since then, and the code has evolved enormously since.

Conclusion:

jsonpath.com is based on an outdated version of JSONPath and is not reliable for previewing what current libraries would provide you with.

Comments