Javascript 如何使用 Node.js 解析 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5726729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:36:08  来源:igfitidea点击:

How to parse JSON using Node.js?

javascriptjsonnode.js

提问by Tikhon Jelvis

How should I parse JSON using Node.js? Is there some module which will validate and parse JSON securely?

我应该如何使用 Node.js 解析 JSON?是否有一些模块可以安全地验证和解析 JSON?

回答by Felix Kling

You can simply use JSON.parse.

您可以简单地使用JSON.parse.

The definition of the JSONobject is part of the ECMAScript 5 specification. node.js is built on Google Chrome's V8engine, which adheres to ECMA standard. Therefore, node.js also has a global object JSON[docs].

JSON对象的定义是 ECMAScript 5 规范的一部分。node.js 建立在 Google Chrome 的V8引擎之上,它遵循 ECMA 标准。因此,node.js 也有一个全局对象[docs]JSON

Note - JSON.parsecan tie up the current thread because it is a synchronous method. So if you are planning to parse big JSON objects use a streaming json parser.

注意 -JSON.parse可以占用当前线程,因为它是一种同步方法。因此,如果您打算解析大型 JSON 对象,请使用流式 json 解析器。

回答by eliocs

you can require.json files.

你可以要求.json 文件。

var parsedJSON = require('./file-name');

For example if you have a config.jsonfile in the same directory as your source code file you would use:

例如,如果您config.json在与源代码文件相同的目录中有一个文件,您将使用:

var config = require('./config.json');

or (file extension can be omitted):

或(文件扩展名可以省略):

var config = require('./config');

note that requireis synchronousand only reads the file once, following calls return the result from cache

请注意,这require同步的并且只读取文件一次,随后的调用从缓存中返回结果

Also note You should only use this for local files under your absolute control, as it potentially executes any code within the file.

另请注意,您应该只将它用于您绝对控制下的本地文件,因为它可能会执行文件中的任何代码。

回答by sampathsris

You can use JSON.parse().

您可以使用JSON.parse().

You should be able to use the JSONobject on any ECMAScript 5compatible JavaScript implementation. And V8, upon which Node.js is built is one of them.

您应该能够JSON在任何ECMAScript 5兼容的 JavaScript 实现上使用该对象。而V8就是其中之一,Node.js 是基于它构建的。

Note: If you're using a JSON file to store sensitive information (e.g. passwords), that's the wrong way to do it. See how Heroku does it: https://devcenter.heroku.com/articles/config-vars#setting-up-config-vars-for-a-deployed-application. Find out how your platform does it, and use process.envto retrieve the config vars from within the code.

注意:如果您使用 JSON 文件来存储敏感信息(例如密码),那是错误的做法。了解 Heroku 是如何做到的:https: //devcenter.heroku.com/articles/config-vars#setting-up-config-vars-for-a-deployed-application。了解您的平台是如何做到的,并用于process.env从代码中检索配置变量。



Parsing a string containing JSON data

解析包含 JSON 数据的字符串

var str = '{ "name": "John Doe", "age": 42 }';
var obj = JSON.parse(str);


Parsing a file containing JSON data

解析包含 JSON 数据的文件

You'll have to do some file operations with fsmodule.

您必须对fs模块进行一些文件操作。

Asynchronous version

异步版本

var fs = require('fs');

fs.readFile('/path/to/file.json', 'utf8', function (err, data) {
    if (err) throw err; // we'll not consider error handling for now
    var obj = JSON.parse(data);
});

Synchronous version

同步版本

var fs = require('fs');
var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));


You wanna use require? Think again!

你想用require吗?再想想!

You can sometimes use require:

您有时可以使用require

var obj = require('path/to/file.json');

But, I do not recommend this for several reasons:

但是,出于以下几个原因,我不建议这样做:

  1. requireis synchronous. If you have a very big JSON file, it will choke your event loop. You really need to use JSON.parsewith fs.readFile.
  2. requirewill read the file only once. Subsequent calls to requirefor the same file will return a cached copy. Not a good idea if you want to read a .jsonfile that is continuously updated. You could use a hack. But at this point, it's easier to simply use fs.
  3. If your file does not have a .jsonextension, requirewill not treat the contents of the file as JSON.
  1. require是同步的。如果您有一个非常大的 JSON 文件,它会阻塞您的事件循环。你真的需要使用JSON.parsewith fs.readFile
  2. require读取文件一次require对同一文件的后续调用将返回缓存副本。如果您想读取.json不断更新的文件,这不是一个好主意。你可以使用hack。但在这一点上,简单地使用fs.
  3. 如果您的文件没有.json扩展名,require则不会将文件内容视为 JSON。

Seriously! Use JSON.parse.

严重地!使用JSON.parse.



load-json-filemodule

load-json-file模块

If you are reading large number of .jsonfiles, (and if you are extremely lazy), it becomes annoying to write boilerplate code every time. You can save some characters by using the load-json-filemodule.

如果您正在阅读大量.json文件(并且如果您非常懒惰),则每次编写样板代码都会变得很烦人。您可以使用该load-json-file模块保存一些字符。

const loadJsonFile = require('load-json-file');

Asynchronous version

异步版本

loadJsonFile('/path/to/file.json').then(json => {
    // `json` contains the parsed object
});

Synchronous version

同步版本

let obj = loadJsonFile.sync('/path/to/file.json');


Parsing JSON from streams

从流中解析 JSON

If the JSON content is streamed over the network, you need to use a streaming JSON parser. Otherwise it will tie up your processor and choke your event loop until JSON content is fully streamed.

如果 JSON 内容通过网络流式传输,则需要使用流式 JSON 解析器。否则它会占用您的处理器并阻塞您的事件循环,直到 JSON 内容完全流式传输。

There are plenty of packages available in NPMfor this. Choose what's best for you.

NPM 中很多可用的包。选择最适合您的。



Error Handling/Security

错误处理/安全

If you are unsure if whatever that is passed to JSON.parse()is valid JSON, make sure to enclose the call to JSON.parse()inside a try/catchblock. A user provided JSON string could crash your application, and could even lead to security holes. Make sure error handling is done if you parse externally-provided JSON.

如果您不确定,如果任何传递给JSON.parse()有效的JSON,请确保调用封装到JSON.parse()一个内部try/catch块。用户提供的 JSON 字符串可能会使您的应用程序崩溃,甚至可能导致安全漏洞。如果您解析外部提供的 JSON,请确保已完成错误处理。

回答by Mark Kahn

use the JSON object:

使用JSON 对象

JSON.parse(str);

回答by pyprism

Another example of JSON.parse :

JSON.parse 的另一个例子:

var fs = require('fs');
var file = __dirname + '/config.json';

fs.readFile(file, 'utf8', function (err, data) {
  if (err) {
    console.log('Error: ' + err);
    return;
  }

  data = JSON.parse(data);

  console.dir(data);
});

回答by Haider

I'd like to mention that there are alternatives to the global JSON object. JSON.parseand JSON.stringifyare both synchronous, so if you want to deal with big objects you might want to check out some of the asynchronous JSON modules.

我想提一下,全局 JSON 对象还有其他选择。 JSON.parse并且JSON.stringify都是同步的,所以如果你想处理大对象,你可能需要查看一些异步 JSON 模块。

Have a look: https://github.com/joyent/node/wiki/Modules#wiki-parsers-json

看看:https: //github.com/joyent/node/wiki/Modules#wiki-parsers-json

回答by Abhishek Verma

Include the node-fslibrary.

包括node-fs图书馆。

var fs = require("fs");
var file = JSON.parse(fs.readFileSync("./PATH/data.json", "utf8"));

For more info on 'fs' library , refer the documentation at http://nodejs.org/api/fs.html

有关“fs”库的更多信息,请参阅http://nodejs.org/api/fs.html 上的文档

回答by Vlad

Since you don't know that your string is actually valid, I would put it first into a try catch. Also since try catch blocks are not optimized by node, i would put the entire thing into another function:

由于您不知道您的字符串实际上是有效的,因此我会将其首先放入 try catch 中。此外,由于 try catch 块不是由节点优化的,我会将整个内容放入另一个函数中:

function tryParseJson(str) {
    try {
        return JSON.parse(str);
    } catch (ex) {
        return null;
    }
}

OR in "async style"

或以“异步风格”

function tryParseJson(str, callback) {
    process.nextTick(function () {
      try {
          callback(null, JSON.parse(str));
      } catch (ex) {
          callback(ex)
      }
    })
}

回答by Burcu Dogan

Parsing a JSON stream? Use JSONStream.

解析 JSON 流?使用JSONStream.

var request = require('request')
  , JSONStream = require('JSONStream')

request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
    .pipe(JSONStream.parse('rows.*'))
    .pipe(es.mapSync(function (data) {
      return data
    }))

https://github.com/dominictarr/JSONStream

https://github.com/dominctarr/JSONStream

回答by debianmaster

JSON.parse("your string");

That's all.

就这样。