如何在节点js中将gson转换为json?
How to convert gson to json in node js?
我想把gson数据改成node js中的json数据,有办法吗?
示例数据 gson
像这样
["test","{\"ID\":0}]
使用https://www.npmjs.com/package/gson
npm install gson
代码示例:
const GSON= require('gson');
const gsonObj = GSON.decode('["test","{\"ID\":0}]');
您不需要任何特别的东西。您必须首先定义或创建对象的正确格式。您的示例格式不正确,也不是 JSON。然后用下面的命令
console.log(JSON.parse("[{\"brand\":\"Jeep\", \"doors\": 3}, {\"brand\":\"Jeep\", \"doors\": 3}]"));
而且如果你的格式不对,转换成JSON
的时候也会遇到这个错误
undefined:1 ["test","{"ID":0}]
^
SyntaxError: Unexpected token I in JSON at position 11
at JSON.parse ()
at Object. (/home/test1.js:24:18)
at Module._compile (internal/modules/cjs/loader.js:805:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:816:10)
at Module.load (internal/modules/cjs/loader.js:672:32)
at tryModuleLoad (internal/modules/cjs/loader.js:612:12)
at Function.Module._load (internal/modules/cjs/loader.js:604:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:868:12)
at internal/main/run_main_module.js:21:11
那是 JSON 字符串吗?我没有看到第一个和最后一个反引号。
如果是,您只需要将其转换为 JSON 对象,例如:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre><code>let jsonString = `
{
"name": "John Doe",
"age": 25,
"tag": ["javascript", "express", "nuxt"]
}
`
let jsonObj = JSON.parse(jsonString)
console.log(jsonObj)
我想把gson数据改成node js中的json数据,有办法吗?
示例数据 gson 像这样
["test","{\"ID\":0}]
使用https://www.npmjs.com/package/gson
npm install gson
代码示例:
const GSON= require('gson');
const gsonObj = GSON.decode('["test","{\"ID\":0}]');
您不需要任何特别的东西。您必须首先定义或创建对象的正确格式。您的示例格式不正确,也不是 JSON。然后用下面的命令
console.log(JSON.parse("[{\"brand\":\"Jeep\", \"doors\": 3}, {\"brand\":\"Jeep\", \"doors\": 3}]"));
而且如果你的格式不对,转换成JSON
的时候也会遇到这个错误undefined:1 ["test","{"ID":0}] ^
SyntaxError: Unexpected token I in JSON at position 11 at JSON.parse () at Object. (/home/test1.js:24:18) at Module._compile (internal/modules/cjs/loader.js:805:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:816:10) at Module.load (internal/modules/cjs/loader.js:672:32) at tryModuleLoad (internal/modules/cjs/loader.js:612:12) at Function.Module._load (internal/modules/cjs/loader.js:604:3) at Function.Module.runMain (internal/modules/cjs/loader.js:868:12) at internal/main/run_main_module.js:21:11
那是 JSON 字符串吗?我没有看到第一个和最后一个反引号。 如果是,您只需要将其转换为 JSON 对象,例如:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre><code>let jsonString = `
{
"name": "John Doe",
"age": 25,
"tag": ["javascript", "express", "nuxt"]
}
`
let jsonObj = JSON.parse(jsonString)
console.log(jsonObj)