如何使用NodeJS和JSON.stringify()创建JSON嵌套对象

时间:2019-04-22 07:05:32

标签: node.js json

我的问题出在port_password中。

{
    "server": "0.0.0.0",
    "server_ipv6": "::",
    "local_address": "127.0.0.1",
    "local_port": 1080,
    "timeout": 120,
    "method": "aes-256-cfb",
    "protocol": "origin",
    "protocol_param": "",
    "obfs": "tls1.2_ticket_auth",
    "obfs_param": "",
    "redirect": "",
    "dns_ipv6": false,
    "fast_open": true,
    "workers": 1,
    "port_password": "{\"10000\":\"pass\",\"10001\":\"pass\",\"10002\":\"pass\",}"
}

我用来生成JSON的代码。

account.forEach(ssr => {

     portsPasswords += JSON.stringify(ssr.port.toString()) + ':' + JSON.stringify(ssr.password.toString()) + ','

})

我想要这样的输出。如何使用NodeJS和JSON.stringfy()实现该目标?

{
    "server": "0.0.0.0",
    "server_ipv6": "::",
    "local_address": "127.0.0.1",
    "local_port": 1080,
    "timeout": 120,
    "method": "aes-256-cfb",
    "protocol": "origin",
    "protocol_param": "",
    "obfs": "tls1.2_ticket_auth",
    "obfs_param": "",
    "redirect": "",
    "dns_ipv6": false,
    "fast_open": true,
    "workers": 1,
    "port_password": {
       "10000":"pass",
       "10001":"pass",
       "10002":"pass"
    }
}

1 个答案:

答案 0 :(得分:1)

const account = [ { port: 10000, password: 'pass1' }, { port: 10001, password: 'pass2' }, { port: 10002, password: 'pass3' } ]; const port_password = account.reduce((a, { port, password }) => { a[port] = password; return a; }, {}); const entireObj = { "server": "0.0.0.0", // etc port_password }; console.log(JSON.stringify(entireObj));改为对象:

pickable_object(pen).
pickable_object(paper).