Languages

Menu
Sites
Language
how to push into json

Hi all!

I have little problem with json.

I have a json file.It's looks like:

{
    "items":
    [
        {
            "title":"some title",
            "url":"some url"
        }    
    ]
    
}

How can I add some data to the json? For example, it should looks like:

{
    "items":
    [
        {
            "title":"some title",
            "url":"some url"
        },
        {
            "title":"other title",
            "url":"other url"
        }
    ]
}

Thanks

Responses

4 Replies
Marco Buettner
var jsonObj = {
    "items":
    [
        {
            "title":"some title",
            "url":"some url"
        }    
    ]
    
};

var array = JSON.parse(jsonObj).items;

var newItem = {"title":"other title", "url":"other url"};

array.push(newItem);

Anton Chernenkov

Thanks. 

But what if I will read json from file?

Now I try to do like:

function getJsonCat(){
	$.getJSON("cats.json",
			function(data){
				var array = JSON.parse(data).items;
				var newItem = {"title":"other title", "url":"other url"};
				array.push(newItem);
                console.log("done!");
			},
            function(){
                cosole.log("error!");
			});
}

And there is a error in console:

"SyntaxError: JSON Parse error: Unexpected identifier "object"

How can I do in this instance?

Marco Buettner
try this var array = JSON.parse(JSON.stringify(data)).items
Anton Chernenkov

Thank you!