1

I have a JavaScript object inside a string and I want to use php to turn this into a JSON. How would you go about this?

<?php $string = '{trees : {key: "value", id: 1}, animals : {key:"value", id: 2}}'; ?>

Important:

This string is not a JSON, but it is a valid JavaScript inside a string. The keys don't have quotes, only the values have quotes (if they are string). So json_decode($string) will not work in this case.

Desired result:

{
   "trees": {
      "key": "value",
      "id": "1"
   },
   "animals": {
      "key": "value",
      "id": "2"
   }
}

I want to turn it into a JSON in php (serverside) so I can pass it back to my JavaScript, decode it and use it as an object.

Or can I just pass it as a string to JS and turn it into an object there? That would also work.

NOTE: I can not change how the string is saved in database. It is and it will remain a string.

TVBZ
  • 564
  • 1
  • 4
  • 15
  • 1
    Anyway... "I want to use php to turn this into a JSON"...sorry but you can't. PHP can't interpret JavaScript. Either change the code which saves it, to store it as valid JSON properly in the DB to begin with, or use PHP to load it into the browser as an object literal and then stringify it to JSON (something like this: http://sandbox.onlinephpfunctions.com/code/48f3b408cdd8f15c1c4f2eaf072c957b347470dc). But I see no obvious sense in saving code into the database if that's not how you want to use it later. JavaScript is code. JSON is a data format. Databases normally store data, not code. – ADyson Jun 19 '20 at 15:22
  • 1
    @ADyson Thanks! Now I know it's not possible. Good. I will see if I can change how it is saved into DB and convert excisting items in DB. I see the JSON in my question did not match the given string, I corrected that. – TVBZ Jun 19 '20 at 15:34
  • 1
    This *may* parse as valid YAML, which you may want to look into… – deceze Jun 19 '20 at 15:36
  • @deceze I will look into that. Thanks. – TVBZ Jun 19 '20 at 15:42
  • how complicated are these strings? if they're all as simple as the example you've given, you could probably get away with a naive regex. You could do a test and dump a bunch of strings, do a simple regex pass to quote keys, and see if they're valid json objects (and do quick iteration tests on each to validate). You should of course still sanitize the strings in the DB, but if they're simple enough this could possibly work, and you could just add a fallback if anything invalid comes out. – user120242 Jun 20 '20 at 04:50

0 Answers0