0

Goodday fellow programmer,

I'm having trouble adding an object to my JSON file. I'm using jQuery. My javascript file:

$('#addchallenge').click(function()
{
    //hardcoded challenge
    var addchallenge =
    {
        "achievementname": "I am an achievement who want to be added to the list",
        "points": "50",
        "comment": "guess who has been a nasty achievement to add"
    }

    $.getJSON("../json/package.json", function (data)
    {
        $.each(data.allachievements, function ()
        {
            //very suspicious line here:
            this["achievementlist"].push(addchallenge);
        });
    });
});

My external JSON file:

{
"allachievements":[
    {
      "name": "list of all achievements",
      "achievementlist": [
        {
          "achievementname": "first achievement",
          "points": "30",
          "comment": "the first achievement to achieve"
        },
        {
          "achievementname": "second achievement",
          "points": "-90",
          "comment": "is worth a negative amout of points"
        },
        {
          "achievementname": "aaand the 3th achievement",
          "points": "30",
          "comment": "do you already have achievement 1 and 2?"
        }]
    }]
}

How could the addchallenge data be added into my JSON file?

Do I need to parse my JSON data, add my challenge to add, then stringify it back?

Thanks in advance :)

Oliver Hader
  • 4,093
  • 1
  • 25
  • 47

4 Answers4

0

You cant directly manipulate the JSON file - Writing, deleting etc.

However, you could write some backend code thats capable of this.

If you simply want to temporally add an achievement, you can parse in your JSON file into a variable and then manipulate it.

Webbanditten
  • 850
  • 9
  • 21
0

You can't modify the JSON file only with client side code. You need some server side code.

I would recommend you to use post().

EDIT: I actually found this: How to : edit an external json file in javascript

So, current post may be considered a duplicate...

Community
  • 1
  • 1
SrAxi
  • 19,787
  • 11
  • 46
  • 65
0

Are you trying to write into a file using jquery?
if so please check the following url:
Read/write to file using jQuery

Community
  • 1
  • 1
Elie Nassif
  • 464
  • 4
  • 11
0

Your problem is this, the context. Inside of the callback you are passing to $.each iterator, this is not what you think it is.

jQuery.each( array, callback )

callback

Type: Function( String propertyName, Object valueOfProperty ) The function that will be executed on every object.

I would change your code like this:

$.getJSON("../json/package.json", function (data)
{
    $.each(data.allachievements, function (key, value)
    {
        value["achievementlist"] = value["achievementlist"] || [];
        value["achievementlist"].push(addchallenge);
    });
});
bluehipy
  • 2,254
  • 1
  • 13
  • 19