如何从nodejs中的JSON检索对象?

发布于 2025-01-21 16:56:27 字数 1214 浏览 1 评论 0原文

拥有此代码:

const fs = require('fs')

const file = 'books.json';

class Book{
  constructor(code) {
    this._code = code;
  }

  get code() {
    return this._code;
  }

  set code(value) {
    this._code = value;
  }
}

async function writeBooks(){
  const data = JSON.stringify([new Book('c1'), new Book('c2')]);
  await fs.promises.writeFile(file, data, 'utf8');
}

async function getBook(code){
  try{
    const data = await fs.promises.readFile(file);
    const array = JSON.parse(data);
    return array.find(b => b.code === code);
  } catch (err){
    console.log(err)
  }
}

writeBooks();
getBook('c1').then(b => console.log(b));

我会得到未定义的(而不是预期的书籍对象)。

  1. 如何获取对象(上述问题)

  2. 如果async函数始终返回承诺,那么我如何返回客户端的对象,而不是他必须调用then()then()< /code>来自getBook(code)

  3. 我是否需要等待 fs.promises.writefile()?就像我在writebooks()中所做的那样?我知道async/等待现在,从等待函数的返回值是数据或错误。但是由于writefile()最多不会返回任何内容,或者最多没有错误(而不是readfile()),为什么我要等待对于没有数据?

Having this code:

const fs = require('fs')

const file = 'books.json';

class Book{
  constructor(code) {
    this._code = code;
  }

  get code() {
    return this._code;
  }

  set code(value) {
    this._code = value;
  }
}

async function writeBooks(){
  const data = JSON.stringify([new Book('c1'), new Book('c2')]);
  await fs.promises.writeFile(file, data, 'utf8');
}

async function getBook(code){
  try{
    const data = await fs.promises.readFile(file);
    const array = JSON.parse(data);
    return array.find(b => b.code === code);
  } catch (err){
    console.log(err)
  }
}

writeBooks();
getBook('c1').then(b => console.log(b));

I am getting undefined (instead of the expecting book object).

  1. How to get the object (the above problem)

  2. If async function always returns promise, how can I then return object for the client, instead of him having to call then() from the getBook(code)?

  3. do I need to await for the fs.promises.writeFile()? as I am doing in writeBooks()? As fas as I understand the async/await now, is that the return value from await function is the data or error. But since the writeFile() does not returns anything, or error at most (as opposed to readFile()) why would I want to await for no data?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

墨落画卷 2025-01-28 16:56:27

实际上,问题的根源不是异步/等待或承诺。问题是试图将数组写入JSON文件。如果您像下面的代码段一样编写JSON数据(作为键值对),则解决了您的问题。

{"1": [new Book('c1').code, new Book('c2').code]} //as a key-value pair

const fs = require('fs')
const file = 'books.json';
class Book{
  constructor(code) {
    this._code = code;
  }
  get code() {
    return this._code;
  }
  set code(value) {
    this._code = value;
  }
}
async function writeBooks(){
  const data = JSON.stringify({"1": [new Book('c1').code, new Book('c2').code]});
  await fs.promises.writeFile(file, data, 'utf8');
}
async function getBook(code){
  try{
    const data = await fs.promises.readFile(file);
    const dataOnJsonFile = JSON.parse(data);
    return dataOnJsonFile["1"];
  } catch (err){
    console.log(err)
  }
}
writeBooks();
getBook('c1').then(b => console.log(b));

Actually the root of problem is not about async/awaits or promises. The problem is trying to write an array to a json file. If you write your json data like the code snippet below (as a key-value pair), your problem is solved.

{"1": [new Book('c1').code, new Book('c2').code]} //as a key-value pair

const fs = require('fs')
const file = 'books.json';
class Book{
  constructor(code) {
    this._code = code;
  }
  get code() {
    return this._code;
  }
  set code(value) {
    this._code = value;
  }
}
async function writeBooks(){
  const data = JSON.stringify({"1": [new Book('c1').code, new Book('c2').code]});
  await fs.promises.writeFile(file, data, 'utf8');
}
async function getBook(code){
  try{
    const data = await fs.promises.readFile(file);
    const dataOnJsonFile = JSON.parse(data);
    return dataOnJsonFile["1"];
  } catch (err){
    console.log(err)
  }
}
writeBooks();
getBook('c1').then(b => console.log(b));

昔日梦未散 2025-01-28 16:56:27
  1. 以上问题是从json.parse返回的书籍只有数据,而不是方法,因此我无法通过获得code获取代码( ){},但仅作为类的公共参数book作为book._code,但是破坏了封装(对话是_ [propery]是私人的,应该有适当的getter/setter)。因此,我将属性公开(并破坏了封装),因为我仍然不知道,如何将方法分配给JSON创建的对象。

  2. 否,async的结果始终是保证。您不能在async中将其解开,客户端将始终必须将其解开。 (因此等待fs.promises.writefile()将将其解开,但随后立即将其包装回,然后在异步函数返回之前。

  3. 如上所述。

  1. The above problem is that the Books returned from JSON.parse have only data, not methods, and thus I cannot get the code via get code(){}, but only as public parameter of class Book as book._code, which however breaks encapsulation (convetion is that _[propery] is private, and there should be appropriate getters/setters). So I made the properties public (and broke encapsulation), because I still don't know, how to assign methods to object created from JSON.

  2. No, the result of async is always Promise. You cannot unwrap it inside async, the client will always have to unwrap it. (so await fs.promises.WriteFile() will unwrap it, but then immediately wrap it back, before async function returns.

  3. as explained above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文