0

From the backend I get a string(nothing I could handle with JSON.parse or JSON.stringify):

"{
  Search_Ids: [
    { "searchId": "428784921" },
    { "searchId": "428784922" },
    { "searchId": "428784923" },
    { "searchId": "428784924" },
    { "searchId": "428784925" }
  ],
  Checksum: 5
}"

I want to convert a JavaScript string to a Javascript object. Using JSON class does not work.

RobG
  • 142,382
  • 31
  • 172
  • 209
Jane Kins
  • 43
  • 1
  • 6
  • 1
    "Does not work" is not an adequate problem description. What is the actual behaviour you observe? – Dai Jan 15 '17 at 11:01
  • 3
    It's not a valid string literal, they can't contain line breaks like that. Remove them. And you can't have unquoted double quotes inside double quotes, etc. – RobG Jan 15 '17 at 11:01
  • Is the problem about keys like `Search_Ids` not quoted in your input? Do you control the backend, is it possible to fix it? – Kos Jan 15 '17 at 11:02
  • 1
    It is also not valid JSON: property names need to be quoted. – trincot Jan 15 '17 at 11:02
  • @RobG, it's more `Search_Ids` and `Checksum` are not quoted correctly. – Nina Scholz Jan 15 '17 at 11:03
  • @NinaScholz—yeah, should have stopped at invalid… ;-) – RobG Jan 15 '17 at 11:03
  • NB: In JavaScript `JSON` is not a class, [but an object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON). – trincot Jan 15 '17 at 11:04
  • 1
    assigning the string to a variable without the quotation marks works like this : `var x={ Search_Ids: [ { "searchId": "428784921" }, { "searchId": "428784922" }, { "searchId": "428784923" }, { "searchId": "428784924" }, { "searchId": "428784925" } ], Checksum: 5 };` with quation marks at the beginning does not work – Jane Kins Jan 15 '17 at 11:05
  • @JaneKins—that is an object literal, it's the notation that JSON is based on but it does not make an object literal "JSON". ;-) – RobG Jan 15 '17 at 11:08
  • There's still a valid question here that hasn't been answered: given a string representing a JavaScript object literal (not JSON), how to safely parse it without eval? @trincot – Kos Jan 15 '17 at 16:01
  • @Kos: Answer to that is: don't. If looking for a *safe* solution, don't accept a back-end sending you JavaScript that you would need to parse. The back-end should use the accepted standard: JSON. – trincot Jan 15 '17 at 16:06

0 Answers0