简体   繁体   English

Javascript - 将对象追加到JSON文件

[英]Javascript - Appending object to JSON File

I currently have an object: 我目前有一个对象:

var obj = {
        username: "James",
        surname: "Brandon",
        id: "[2]"
}

and I want to append it to "users.json": 我想将它附加到“users.json”:

[
  {    
    "username": "Andy",
    "surname": "Thompson",
    "id": [0],
  },
  {    
    "username": "Moe",
    "surname": "Brown",
    "id": [1]
  }
]

Do you know how I might be able to do this? 你知道我怎么能这样做吗? Thanks in advance. 提前致谢。

If your code is running in the browser and users.json is an output file, I guess you already have access to its content. 如果您的代码在浏览器中运行且users.json是输出文件,我猜您已经可以访问其内容。

Use the push() method . 使用push()方法

Also, note the missing commas in your objects. 另外,请注意对象中缺少的逗号。

 var obj = { username: "James", surname: "Brandon", id: "[2]" }; var users = [ { "username": "Andy", "surname": "Thompson", "id": [0] }, { "username": "Moe", "surname": "Brown", "id": [1] } ]; users.push(obj); console.log( JSON.stringify(users) ); 

Now that you have the updated array of objects you can upload it to the server (check this question ) or offer a download to the user (check this other question ). 现在您已经拥有更新的对象数组,您可以将其上传到服务器(查看此问题 )或向用户提供下载(请查看其他问题 )。

As you have been already told, there is no way to directly update client-side a file in the server. 正如您已经被告知的那样,无法直接更新服务器中的客户端文件。 It is also not possible to save it directly into the client filesystem. 也无法将其直接保存到客户端文件系统中。

This answer is assuming that you are working under Node.js. 这个答案假设你在Node.js下工作。

As I understand your problem you need to solve a few different programming questions. 正如我理解你的问题,你需要解决一些不同的编程问题。

  1. read and write a .json file 读写.json文件

     const fs = require("fs"); let usersjson = fs.readFileSync("users.json","utf-8"); 
  2. transform a json string into a javascript array 将json字符串转换为javascript数组

     let users = JSON.parse(usersjson); 
  3. append an object to an array 将对象附加到数组

     users.push(obj); 
  4. transform back the array into a json string 将数组转换回json字符串

     usersjson = JSON.stringify(users); 
  5. save the json file 保存json文件

     fs.writeFileSync("users.json",usersjson,"utf-8"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM