最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何在JavaScript中从JSON解析对象并避免[Function(匿名)]?

网站源码admin30浏览0评论

如何在JavaScript中从JSON解析对象并避免[Function(匿名)]?

如何在JavaScript中从JSON解析对象并避免[Function(匿名)]?

我有一个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

{
    "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'));

节点终端的输出

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

评论列表(0)

  1. 暂无评论