[英]Node JS String Inside Curly Brackets
// My input String
// Could be on : true, on : false, bri : 255, etc, etc
var inputString = 'on : true'
console.log(inputString);
var wrongResult = { inputString }
console.log(wrongResult);
// The result that I am trying to achieve
var desiredResult = {
on : true
}
console.log(desiredResult);
Run it: https://repl.it/LCDt/4 运行它: https : //repl.it/LCDt/4
I created the above code snippet to demonstrate the problem that I am experiencing. 我创建了以上代码片段,以演示我遇到的问题。 I have an input string that I receive that could be "on : true", "on : false", "bri : 250", "sat : 13", etc. When posting this data to a server, the format that works is seen above as the "desireResult". 我收到的输入字符串可能是“ on:true”,“ on:false”,“ bri:250”,“ sat:13”等。将这些数据发布到服务器时,可以使用的格式为在上方显示为“ desireResult”。
But, when taking a string, such as 'on : true', in a variable, and placing it inside {}, it always seems to create a dictionary with the variable name as the key and the string itself as the value. 但是,当将一个字符串(例如“ on:true”)放入一个变量中,并将其放在{}内时,似乎总是创建一个以变量名作为键,字符串本身作为值的字典。
Can someone explain why this is and how to get around it? 有人可以解释为什么会这样以及如何解决吗?
Can someone explain why this is 有人可以解释为什么
Because the syntax { foo }
means "Create an object, give it a property called foo
, give that property the value of the foo
variable. 因为语法{ foo }
意思是“创建一个对象,给它一个名为foo
的属性,然后给该属性foo
变量的值。
how to get around it 如何解决它
Parse the data. 解析数据。 Assign it explicitly. 明确分配。
Start by splitting the string on :
. 首先在以下位置分割字符串:
Then remove the white space. 然后删除空白。 Then test is the second value is a number or a keyword. 然后测试第二个值是数字还是关键字。 And so on. 等等。
This would be easier if the data you were receiving was in a standard format. 如果您要接收的数据是标准格式,这会更容易。 Then you could use an existing parser. 然后,您可以使用现有的解析器。 If you have control over the input: Change it to be valid JSON and then use JSON.parse
. 如果您可以控制输入:将其更改为有效JSON,然后使用JSON.parse
。
You could use JSON.parse for that but you need to feed him valid JSON. 您可以使用JSON.parse,但是您需要向他提供有效的JSON。 You need to have an string in form of: 您需要使用以下形式的字符串:
{"on":true}
using JSON.parse('{"on":true}') will return you the desired object. 使用JSON.parse('{“ on”:true}')将返回您想要的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.