1

I have PHP code that takes a list of filename or empty strings and puts them in an array. This array is converted into JSON and stored in a database, this works fine. However, the array is also stored in an object. The issue is when I decode the JSON string of the object. I am running into an error when I try to parse this JSON string in JavaScript: (I don't want to show the rest of the JSON due to privacy)

{"dateCreated":"2022-02-02","dateTimeCreated":"2022-02-02T20:47","title":"lovesick","images":["","","D:\xampp\htdocs\...

Error:

VM8206:1 Uncaught SyntaxError: Unexpected token x in JSON at position 107 at JSON.parse () at new_log.php:33:50

The error is clearly due to the \ being an escape character in JSON but I have tried entering the string into the array with an escape to escape the escape: 'D:\\xampp\\htdocs\...' and this still gives me the same error - I have even tried \\ and \\ but they just give a slightly different error.

If I put the array into the object as a JSON string then I get the error:

VM8178:1 Uncaught SyntaxError: Unexpected string in JSON at position 96 at JSON.parse () at new_log.php:33:50

despite it being the exact same JSON string as shown above?!

Does anyone know how I can fix this issue? Is there some other way I should be storing filenames in JSON?

Olly V
  • 23
  • 4
  • can't you just ```addslashes($json_data)``` when storing and stripslashes($json_data) when reading ? – futureweb Feb 02 '22 at 21:30
  • https://stackoverflow.com/questions/32056940/how-to-deal-with-backslashes-in-json-strings-php – 1sina1 Feb 02 '22 at 21:33
  • 1
    thanks @futureweb I didn't know that existed – Olly V Feb 02 '22 at 21:52
  • You need to show the code that produces the problematic string, because _that_ is where the problem lies. Using `add/stripslashes()` is generally a code smell. – Sammitch Feb 03 '22 at 20:49

1 Answers1

1

Hey mate what you need to do is Escape your backslashes in your images array.

Here is what I have done in the console: escaped string working

What you need to do is format your Json data before you send it across the line:

Here is a similar question and answer that will help : How to escape special characters in building a JSON string?

Sweet Chilly Philly
  • 3,014
  • 2
  • 27
  • 37
  • Thanks for the reply. I have tried that but the string is entered into a PHP variable. When I echo this variable it does not include the escape slash for the real slash (I enter D:\\xampp it echos D:\xampp). I don't know how to fix this – Olly V Feb 02 '22 at 21:39
  • I have managed to get it working with four backslashes! Not sure why this wasn't working before. – Olly V Feb 02 '22 at 21:49
  • Yeah it seems like PHP is cleaning your input somewhere, so adding more backslashes means PHP is still cleaning the input, but it cleans two backslashes to a single 1 so therefore it fits in the JSON format – Sweet Chilly Philly Feb 02 '22 at 21:50