【问题标题】:How to parse objects from JSON in JavaScript and avoid [Function (anonymous)]?如何在 JavaScript 中解析 JSON 中的对象并避免 [Function (anonymous)]?
【发布时间】:2020-08-21 15:26:33
【问题描述】:

我有一个 JSON 文件,其中包含一个对象“books”:

{
    "books": {
        "book1": {
            "name": "Smth1",
            "about": "Тут <b>описание</b> <i>книги</i>",
            "file": "id",
            "fileDesc": "Текст к файлу"
        },
        "book2": {
            "name": "Smth2",
            "about": "Тут <b>описание</b> <i>книги</i>",
            "file": "id",
            "fileDesc": "Текст к файлу"
        }
    }
}

我需要这个对象。但是当我从文件中读取一个对象并打印它时:

const obj = require('./file.json').books
console.log(obj)

我明白了:

  book1: {
    name: [Function (anonymous)],
    about: [Function (anonymous)],
    file: [Function (anonymous)],
    fileDesc: [Function (anonymous)]
  },
  book2: {
    name: [Function (anonymous)],
    about: [Function (anonymous)],
    file: [Function (anonymous)],
    fileDesc: [Function (anonymous)]
  }
}

并且不能使用对象。我该如何解决?

【问题讨论】:

  • 这个 json 文件看起来不像是有效的语法。没有顶级括号。
  • 请检查大括号的平衡,并将 JSON 描述为有效的 JSON。 JSON 不能以"books": 开头,如果是对象,它应该以{ 开头。但更重要的是,“并且不能使用对象”是什么意思?如果您能够使用console.log 输出它,那么您就有一个有效的对象。那么有什么问题呢?
  • 大家好!感谢您的建议。正如我所写,这只是 JSON 文件中的一个对象,坚果完整文件
  • 您意识到console.log 输出与JSON.stringify 不同
  • 你的解析器在做一些奇怪的事情,JSON 甚至不能存储函数。

标签: javascript node.js json object


【解决方案1】:

使其成为正确的 json

{
    "books": {
        "book1": {
            "name": "Smth1",
            "about": "Тут <b>описание</b> <i>книги</i>",
            "file": "id",
            "fileDesc": "Текст к файлу"
        },
        "book2": {
            "name": "Smth2",
            "about": "Тут <b>описание</b> <i>книги</i>",
            "file": "id",
            "fileDesc": "Текст к файлу"
        }
    }
}

现在你可以阅读了

var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('books.json', 'utf8'));

Node 终端的输出

> obj
{
  books: {
    book1: {
      name: 'Smth1',
      about: 'Тут <b>описание</b> <i>книги</i>',
      file: 'id',
      fileDesc: 'Текст к файлу'
    },
    book2: {
      name: 'Smth2',
      about: 'Тут <b>описание</b> <i>книги</i>',
      file: 'id',
      fileDesc: 'Текст к файлу'
    }
  }
}
> 

【讨论】:

    【解决方案2】:

    仅在 file.js 中添加花括号:

    {
        "books": {
            // ..
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2015-12-21
      • 2021-12-28
      • 2020-01-23
      • 2014-12-02
      相关资源
      最近更新 更多