Finding and editing nested JSON elements

Basically, I want Javascript (jQuery optional) to search in JSON with nested elements for a specific element and edit it.

Ex. Search for “components” with ID 110 and change the name to “video card”.

Take a look at the following JSON example. I am wondering if javascript libraries or good tricks exist, I don’t think the best solution for all json or writing my own methods is the best solution.

{
   "computers": [
   {
     "id": 10,
     "components": [
         {
           "id": 56,
           "name": "processor"
         },
         {
           "id": 24,
           "name": "ram"
        }
      ]
    },
    {
      "id": 11,
      "components": [
        {
          "id": 110,
          "name": "graphic card"
        },
        {
          "id": 322,
          "name": "motherboard"
        }
      ]
    }
  ]
}
+5
source share
2 answers

You can try linq.js .

+2
source

javascript lib, DefiantJS (http://defiantjs.com), XPath JSON. JS:

var data = {
       "computers": [
          {
             "id": 10,
             "components": [
                { "id": 56, "name": "processor" },
                { "id": 24, "name": "ram" }
             ]
          },
          {
             "id": 11,
             "components": [
                { "id": 110, "name": "graphic card" },
                { "id": 322, "name": "motherboard" }
             ]
          }
       ]
    },
    res = JSON.search( data, '//components[id=110]' );

res[0].name = 'video card';

;
http://jsfiddle.net/g8fZw/

DefiantJS JSON "" ( , ). lib XPath XPath Evaluator:

http://www.defiantjs.com/#xpath_evaluator

+1

All Articles