1

I'm using Node.js v4.2.2 with ES6. I read a file that represents an object containing multiline strings. My file looks like:

{"a":`b
      c`};

I read the file into a string:

var fs = require ('fs');
var my_string = fs.readFileSync(path_to_my_file).toString();

Finally, from that string I'd like to obtain the object that it represents. The only option I can find is using eval:

eval('my_object = ' + my_string);

is there another way? Note that JSON.parse(my_string) is not an option because multiline strings are not part of JSON standard.

Gabriel Furstenheim
  • 2,969
  • 30
  • 27
  • 1
    where does that string come from? – Daniel A. White Jan 27 '16 at 14:32
  • 1
    Replace the backticks with double quotes and you should be able to `JSON.parse` it. As it stands now, it's not valid JSON. – gen_Eric Jan 27 '16 at 14:35
  • 1
    The backticks *inside* this string are *not* special and this is *not* an ES6 multi-line/template string. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings – gen_Eric Jan 27 '16 at 14:36
  • The string comes from a file I'm reading. Replacing with double quotes is not an option, as there might be double quotes inside the string. – Gabriel Furstenheim Jan 27 '16 at 14:39
  • 1
    @GabrielFurstenheim: Is it possible to edit this file so that the lines in it are valid JSON? – gen_Eric Jan 27 '16 at 14:40
  • how about replacing them with a another string you're unlikely to encounter, e.g. "#%--foobar666µ*!", and convert back the property after parsing? Any solution will be better than implementing your own JSON parser. – Antoine Jan 27 '16 at 14:41
  • 1
    There's no need to use interpolation on strings coming out of files either, interpolation is only needed when parsing the script and when it has an actual newline character, `\n` are still fine in normal strings. – MinusFour Jan 27 '16 at 14:42
  • @RocketHazmat Not really. The strings in question represent long SQL queries. Multiline strings are the only way to make the readable. – Gabriel Furstenheim Jan 27 '16 at 14:58
  • @MinusFour I'm not sure I understand your point. Do you say that I can use normal quotes and I won't have problems with \n? I've edited my question to show that I do have actual newlines. – Gabriel Furstenheim Jan 27 '16 at 14:58

1 Answers1

3

If you don't like to eval the expression, you can always throw an ES6 parser (like esprima) at it, so that you can manually and securely evaluate the parts that you're interested in.

But the proper way would be not to use object literals with multiline template strings in the first place, and store your data as JSON instead.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 2
    which fyi would look like this: `{"a":"b\n      c"}` (ah, come on, Stackoverflow got rid of the spaces, so I replaced them with non-breaking spaces) – Nebula Jan 27 '16 at 14:59