JSONPath Syntax when dot in key

跟風遠走 提交于 2019-12-10 18:20:56

问题


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?


回答1:


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.




回答2:


Having a json response:

{
  "0": {
    "SKU": "somevalue",
    "Merchant.Id": 234
    }
}

I can target a key with a . (dot) in the name.

jsonPath.getJsonObject("0.\"Merchant.Id\"")

Note: the quotes and the fact that they are escaped.

Note not sure of other versions, but I'm using

'com.jayway.restassured', name: 'json-path', version: '2.9.0'

A few samples/solutions I've seen, was using singe quotes with brackets, but did not work for me.



来源:https://stackoverflow.com/questions/40187231/jsonpath-syntax-when-dot-in-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!