将未定义的JSON投射到新的JSON对象中
未定义的JSON从URL api端点http : // someserver:someport / some_api_url?_var1=1
返回到Node.js / Express.js应用程序。 这个未定义的JSONinput将始终具有相同的格式,需要通过接收代码(如下所示)将其转换为新的JSON对象。 新的JSON对象然后可以以各种方式进行处理,包括被传递到HTML。
OP问题:
需要对下面的代码做出什么特殊的改变,以便:
1.) {"1":"descriptive string"}
forms的JSON被dataElement
为一个新定义的名为dataElement
JSON对象, dataElement
包含两个属性dataElement.dataKey
和dataElement.descriptionString
?
2.)发送回用户的Web浏览器的html响应包括UI格式的dataElement.dataKey
和dataElement.descriptionString
:
Index is: 1 Description is: descriptive string
示例代码将被修改:
对于初学者来说,需要修改的代码是:
app.get('/', function (req, res) { var url = 'http://someserver:someport/some_api_url?_var1=1' http.get(url, function (resInner) { var body = ''; resInner.on('data', function (chunk) { body += chunk; }); resInner.on('end', function () { var fullResponse = JSON.parse(body); // code to parse JSON into new JSON object, which is passed into HTML var indexStr = key; var descriptionStr = fullResponse[key]; var dataElement = {"dataKey" : key, "descriptionString" : descriptionStr}; var htmlResp = 'Index is: '+${dataElement.dataKey}+'<br> Description is: '+${dataElement.descriptionString}; res.send(htmlResp); }); }).on('error', function (e) { console.log("Got an error: ", e); }); });
当前错误:
目前,上面的代码给出了以下错误:
/home/user/nodejs_apps/express_helloworld/myapp/app.js:139 var htmlResp = 'Index is: '+${dataElement.dataKey}+'<br> Description is: '+${dataElement.descriptionString}; ^ SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:387:25) at Object.Module._extensions..js (module.js:422:10) at Module.load (module.js:357:32) at Function.Module._load (module.js:314:12) at Function.Module.runMain (module.js:447:10) at startup (node.js:142:18) at node.js:939:3
错误是来自你的string连接,这似乎是使用一些无效的模板语言,而key
variables,这是没有定义,你必须实际得到的关键与Object.keys
等
试试这个方法
app.get('/', function(req, res) { var url = 'http://someserver:someport/some_api_url?_var1=1' http.get(url, function(resInner) { var body = ''; resInner.on('data', function(chunk) { body += chunk; }); resInner.on('end', function() { var fullResponse = JSON.parse(body); // code to parse JSON into new JSON object, which is passed into HTML var keys = Object.keys(fullResponse); var firstKey = keys[0]; var descriptionStr = fullResponse[firstKey]; var dataElement = { "dataKey": firstKey, "descriptionString": descriptionStr }; var htmlResp = 'Index is: ' + dataElement.dataKey + '<br> Description is: ' + dataElement.descriptionString; res.send(htmlResp); }); }).on('error', function(e) { console.log("Got an error: ", e); }); });
在这个例子中,你正在尝试使用模板string ,但是你正在使用它们,导致错误。 这是模板string的格式:
`Hello World, the expression "1+2" evaluates to ${1+2}` ==> `Hello World, the expression "1+2" evaluates to 3`
模板string使用反引号,你用什么来在SE插入内联代码。 所以,你的问题线应该是这样的:
var htmlResp = `Index is: ${dataElement.dataKey}`<br> Description is: `${dataElement.descriptionString}`;
除了那个语法错误之外,我看不出你的代码有什么问题,但是谁知道呢? ;)
希望我能帮上忙!