1
  // 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?

Archetype90
  • 179
  • 1
  • 4
  • 19
  • you could also [load the string as a module](https://stackoverflow.com/questions/17581830/load-node-js-module-from-string-in-memory) with a bit of decorating on the input before hand. edit: I assumed node, I realise that's a big assumption. gonna leave this comment just in case. – rlemon Sep 13 '17 at 13:07

2 Answers2

1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • @JaredSmith — Won't work. The `on` is not surrounding with quote characters. – Quentin Sep 13 '17 at 12:50
  • @JaredSmith — Dangerous. Very dangerous. I suggested writing a proper parser instead of using hacks like that intentionally. – Quentin Sep 13 '17 at 12:52
-1

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.

Coldblue
  • 144
  • 2
  • 8