-3

I have this JSON file

projectsJSON =  [
    {"name" : "Hotel"},
    {"name" : "Inventory"},
    {"name" : "Corp. Manager"}
];

And this code in `javascript.js

    let getProjects = projectsJSON
    getProjects.push({
        "name":name
    });
    projectsJSON = JSON.stringify(getProjects);`

My goal is to add a new object to projectsJSON,but this code is not working.When i print out projectsJSON it does show the added object,but file doesn't get changed.

  • "I have this JSON file" — That is not valid JSON. – Quentin Oct 20 '17 at 17:36
  • 1
    You first example is not a JSON file. It's (presumably) JavaScript that assigns an array to the variable `projectsJSON`. *"but file doesn't get changed"* To do that you would have to write to the file system. And you would only be able to do that if your code runs in an environment that has access to the file system. If this is client side code then you actually have to write a server that accepts input from the client and writes to the file system. – Felix Kling Oct 20 '17 at 17:36
  • Please have a look at [**this**](https://stackoverflow.com/questions/18884840/adding-a-new-array-element-to-a-json-object) –  Oct 20 '17 at 17:36
  • @Quentin what is wrong with it and how can i fix it? – user8615957 Oct 20 '17 at 17:36
  • You can't change a file with javascript. Not without using any filesystem features if it has. And that's an inline javascript object array. Not a file. – Taha Paksu Oct 20 '17 at 17:36
  • Potentially a duplicate of [Read/write json from js to file on server (not server app)](https://stackoverflow.com/q/4840727/218196) – Felix Kling Oct 20 '17 at 17:40

1 Answers1

0

You cannot do that using JavaScript running in the browser because it does not have access to read / modify the filesystem

linasmnew
  • 3,907
  • 2
  • 20
  • 33