0

I need to push an an object into an array in in a Json file. To make it simple lets say that my Json looks like this:

var JsonObj = {
"elements" : []
}

I tried Push() method but it didnt work. tried also to assign to JsonObj.elements[0]= ... it also fails. How can i make it work?

7
  • 1
    That's not JSON, it's JavaScript. Commented Apr 1, 2015 at 15:09
  • 1
    "I need to push an an object into an array in in a Json file." You can't really modify a file with client side JavaScript. Please provide more information. Commented Apr 1, 2015 at 15:17
  • If u target - at re-write file ON server - u have to ajax to back-end (ruby, nodejs, php and etc..) and re-write file in back-end with data from javascript throw ajax Commented Apr 1, 2015 at 15:18
  • @FelixKling I do plan to modify a json object locally.. Commented Apr 1, 2015 at 15:25
  • So you don't actually want to write to a file? You simply want to mutate a JavaScript object/array? Commented Apr 1, 2015 at 15:31

2 Answers 2

1

Try that way, it has to work:

JsonObj.elements.push(1);

FIddle: https://jsfiddle.net/29qa4bfw/1/

Sign up to request clarification or add additional context in comments.

Comments

0

This is basic Javascript. nothing to do with Json or jQuery:

var jsonObj = {
"elements" : []
};

jsonObj.elements.push(1);
jsonObj.elements.push(1.5);
jsonObj.elements.push("some text");
jsonObj.elements.push({element: "some element"});

Here's a jsbin to fool around with: http://jsbin.com/hajale/2/edit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.