-1

I get from db this string:

{ from: 15.00, to: 16.00 },
{ from: 16.00, to: 17.00 },
{ from: 17.00, to: 18.00 },
{ from: 18.00, to: 19.00 }

It is a string and json.parse not work in this case. Is it possible to convert this string to regular js object?

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
Jalson1982
  • 287
  • 4
  • 14
  • 5
    Why is it not returning a valid JavaScript code? Adding [ and ] would make it work.... – epascarello Feb 25 '19 at 14:11
  • 1
    This is an array elements, it needs to be in square brackets i.e. `[``]`, then you can parse it to json – Prasad Telkikar Feb 25 '19 at 14:14
  • https://en.wikipedia.org/wiki/JSON_streaming#Line-delimited_JSON? Although it's not even proper JSON (missing quotes). – Bergi Feb 25 '19 at 14:21
  • _This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting._ – mplungjan Feb 25 '19 at 14:23

2 Answers2

3

Your current database output isn't parsable because it isn't considered valid JSON. You have a few options to fix this issue:

  1. Store your string in your database as a stringified object so that when you need to parse it, it can be done easily.

  2. Use regex to reformat your string so that it is parsable using JSON.parse. This involves making each key a string.

  3. You can "loosely" parse your JSON. However, this isn't recommended as it opens your javascript up to injection attacks and other vulnerabilities.

Reformatting your string:

const str = "{ from: 15.00, to: 16.00 },{ from: 16.00, to: 17.00 },{ from: 17.00, to: 18.00 },{ from: 18.00, to: 19.00 }",
parsable = str.replace(/(\w+):/g, '"$1":'),

obj = JSON.parse("[" +parsable +"]");
console.log(obj);

"Loosely" parsing your JSON with a Function constructor: - (Not recommended)

const str = "{ from: 15.00, to: 16.00 },{ from: 16.00, to: 17.00 },{ from: 17.00, to: 18.00 },{ from: 18.00, to: 19.00 }",

obj = (Function("return [" + str + "]"))();
console.log(obj);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

It is already parsed in JavaScript JSON syntax, you just need to enclose it in "[]" square braces. and you can directly access it as it is already parsed. You can test for first object using...

  objArray=[ 
      { from: 15.00, to: 16.00 },
      { from: 16.00, to: 17.00 },
      { from: 17.00, to: 18.00 },
      { from: 18.00, to: 19.00 } 
    ];
console.log("From : " + objArray[0].from + " To : " + objArray[0].to);