开发者

How to set a deeply nested JSON value?

开发者 https://www.devze.com 2023-02-16 14:15 出处:网络
For the JSON below, I want to add/update an item to \"bonuses\".Is there a way I can direc开发者_StackOverflow中文版tly put a the variable {\"name\": \"ham\", \"bonus\": 12} ?

For the JSON below, I want to add/update an item to "bonuses". Is there a way I can direc开发者_StackOverflow中文版tly put a the variable {"name": "ham", "bonus": 12} ?

{
    "abilities": {
        "FGI": {
            "score": 10,
            "mod": 1,
            "bonuses": [
                {
                    "name": "spam",
                    "bonus": 1 
                },
                {
                    "name": "eggs",
                    "bonus": 1 
                } 
            ] 
        } 
    }
} 

NOTE: I should clarify that the "JSON" is a Python Object built from a JSON String.


abilities.FGI.bonuses.push({"name": "ham", "bonus": 12});

EDIT or:

abilities["FGI"]["bonuses"].push(..);


That'll be a fun one! There isn't really an easy (built-in) way to do it. In markusf's answer, he mentions pushing at item on the end, but that's only half of your problem. If you want to make sure there's not already a "ham" item in there, you'll have to loop through it using a function like this:

function array_has_item_already(array, key, look_for_key_value) {
  for( var i = 0; i < array.length; i++) {
    if( typeof array[i][key] != 'undefined' && array[i][key] == look_for_key_value )
      return array[i];
  }
  return false;
}

you'd call it like this, and it would return false if it didn't find the item:

array_has_item_already(abilities.FGI.bonuses, "name", "ham");

I'll leave it to you to push the function out to make it update or push or whatever. Have fun!

UPDATE

I just realized that you're looking for something in python. Welp, you can completely disregard my answer, or translate it, as it's in js. HA.

0

精彩评论

暂无评论...
验证码 换一张
取 消