2013-10-16 76 views
0

我在使用JSONPath做某些事情時遇到了一些麻煩。這是我有:JSONPath模式 - 保持對象結構

[ 
    { 
     "id": { 
      "type": "literal", 
      "value": "123456789", 
      "datatype": "http://www.w3.org/2001/XMLSchema#string" 
     }, 
     "name": { 
      "type": "literal", 
      "value": "John Doe", 
      "datatype": "http://www.w3.org/2001/XMLSchema#string" 
     } 
    }, 
    { 
     "id": { 
      "type": "literal", 
      "value": "2123456789", 
      "datatype": "http://www.w3.org/2001/XMLSchema#string" 
     }, 
     "name": { 
      "type": "literal", 
      "value": "Jane Doe", 
      "datatype": "http://www.w3.org/2001/XMLSchema#string" 
    } 
} 

] } ]

而我想應用模式後,得到的是:

[ 
    { 
     "id": "123456789", 
     "name": "John Doe" 

    }, 
    { 
     "id": "2123456789", 
     "name": "Jane Doe" 

    } 
] 

這可能嗎?我正在做的最好的是["123456789", "John Doe","2123456789","Jane Doe"]

模式應該是什麼樣子?

回答

-1

使用DefiantJS(http://defianjs.com),您可以使用XPath表達式查詢JSON結構。 DefiantJS使用「搜索」方法擴展全局對象JSON,並將匹配返回爲類似數組的對象。

這是一個示例代碼;

var data = [ 
     { 
      "id": { 
      "type": "literal", 
      "value": "123456789", 
      "datatype": "http://www.w3.org/2001/XMLSchema#string" 
      }, 
      "name": { 
      "type": "literal", 
      "value": "John Doe", 
      "datatype": "http://www.w3.org/2001/XMLSchema#string" 
      } 
     }, 
     { 
      "id": { 
      "type": "literal", 
      "value": "2123456789", 
      "datatype": "http://www.w3.org/2001/XMLSchema#string" 
      }, 
      "name": { 
      "type": "literal", 
      "value": "Jane Doe", 
      "datatype": "http://www.w3.org/2001/XMLSchema#string" 
      } 
     } 
    ], 
    found = JSON.search(data, '//value'), 
    str = ''; 

for (var i=0; i<found.length; i++) { 
    str += found[i] +'<br/>'; 
} 

document.getElementById('output').innerHTML = str; 

要看到這個代碼的行動,看看這個小提琴; http://jsfiddle.net/hbi99/4BZMm/

有關更多有用的XPath表達式,請參閱此處的類似XPath評估程序; http://defiantjs.com/#xpath_evaluator