How to parse JSON using Node.js?

2018-12-31 10:30发布

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

30条回答
浪荡孟婆
2楼-- · 2018-12-31 11:05

Use JSON.parse(str);. Read more it here.

Here are some examples:

var jsonStr = '{"result":true, "count":42}';

obj = JSON.parse(jsonStr);

console.log(obj.count);    //expected output: 42
console.log(obj.result);   // expected output: true
查看更多
永恒的永恒
3楼-- · 2018-12-31 11:05
var fs = require('fs');

fs.readFile('ashish.json',{encoding:'utf8'},function(data,err) {

   if(err) 
      throw err;

   else {

   console.log(data.toString());

 }
})
查看更多
怪性笑人.
4楼-- · 2018-12-31 11:06

Using JSON for your configuration with Node.js? Read this and get your configuration skills over 9000...

Note: People claiming that data = require('./data.json'); is a security risk and downvoting people's answers with zealous zeal: You're exactly and completely wrong. Try placing non-JSON in that file... Node will give you an error, exactly like it would if you did the same thing with the much slower and harder to code manual file read and then subsequent JSON.parse(). Please stop spreading misinformation; you're hurting the world, not helping. Node was designed to allow this; it is not a security risk!

Proper applications come in 3+ layers of configuration:

  1. Server/Container config
  2. Application config
  3. (optional) Tenant/Community/Organization config
  4. User config

Most developers treat their server and app config as if it can change. It can't. You can layer changes from higher layers on top of each other, but you're modifying base requirements. Some things need to exist! Make your config act like it's immutable, because some of it basically is, just like your source code.

Failing to see that lots of your stuff isn't going to change after startup leads to anti-patterns like littering your config loading with try/catch blocks, and pretending you can continue without your properly setup application. You can't. If you can, that belongs in the community/user config layer, not the server/app config layer. You're just doing it wrong. The optional stuff should be layered on top when the application finishes it's bootstrap.

Stop banging your head against the wall: Your config should be ultra simple.

Take a look at how easy it is to setup something as complex as a protocol-agnostic and datasource-agnostic service framework using a simple json config file and simple app.js file...

container-config.js...

{
    "service": {
        "type"  : "http",
        "name"  : "login",
        "port"  : 8085
    },
    "data": {
        "type"  : "mysql",
        "host"  : "localhost",
        "user"  : "notRoot",
        "pass"  : "oober1337",
        "name"  : "connect"
    }
}

index.js... (the engine that powers everything)

var config      = require('./container-config.json');       // Get our service configuration.
var data        = require(config.data.type);            // Load our data source plugin ('npm install mysql' for mysql).
var service     = require(config.service.type);         // Load our service plugin ('http' is built-in to node).
var processor   = require('./app.js');                  // Load our processor (the code you write).

var connection  = data.createConnection({ host: config.data.host, user: config.data.user, password: config.data.pass, database: config.data.name });
var server      = service.createServer(processor);
connection.connect();
server.listen(config.service.port, function() { console.log("%s service listening on port %s", config.service.type, config.service.port); });

app.js... (the code that powers your protocol-agnostic and data-source agnostic service)

module.exports = function(request, response){
    response.end('Responding to: ' + request.url);
}

Using this pattern, you can now load community and user config stuff on top of your booted app, dev ops is ready to shove your work into a container and scale it. You're read for multitenant. Userland is isolated. You can now separate the concerns of which service protocol you're using, which database type you're using, and just focus on writing good code.

Because you're using layers, you can rely on a single source of truth for everything, at any time (the layered config object), and avoid error checks at every step, worrying about "oh crap, how am I going to make this work without proper config?!?".

查看更多
若你有天会懂
5楼-- · 2018-12-31 11:09

use the JSON object:

JSON.parse(str);
查看更多
查无此人
6楼-- · 2018-12-31 11:09

You can use JSON.parse() (which is a built in function that will probably force you to wrap it with try-catch statements).

Or use some JSON parsing npm library, something like json-parse-or

查看更多
怪性笑人.
7楼-- · 2018-12-31 11:09

I use fs-extra. I like it a lot because -although it supports callbacks- it also supports Promises. So it just enables me to write my code in a much more readable way:

const fs = require('fs-extra');
fs.readJson("path/to/foo.json").then(obj => {
    //Do dome stuff with obj
})
.catch(err => {
    console.error(err);
});

It also has many useful methods which do not come along with the standard fs module and, on top of that, it also bridges the methods from the native fs module and promisifies them.

NOTE: You can still use the native Node.js methods. They are promisified and copied over to fs-extra. See notes on fs.read() & fs.write()

So it's basically all advantages. I hope others find this useful.

查看更多
登录 后发表回答