简体   繁体   中英

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

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".

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.

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.

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 .

You could use JSON.parse for that but you need to feed him valid JSON. You need to have an string in form of:

    {"on":true}

using JSON.parse('{"on":true}') will return you the desired object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM