-19

I have some URLs in my database, and I want to print them as JSON using PHP. How can I get the desired format, without escaping backslashes, in my JSON object?

// Business to get data
...
// print JSON data
echo json_encode($customer, JSON_UNESCAPED_UNICODE);

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James
  • 1,190
  • 5
  • 27
  • 52

1 Answers1

16

This sounds like a typical XY problem. There are very few situations where you would want to unescape JSON (and I say this to be polite, I can't think of a single one) and in your case, your code suggests you echo that JSON so it can be consumed elsewhere.

Elsewhere probably means on a client with JavaScript. There is the JSON.parse function that does exactly what you want, and more: it transforms JSON (correct JSON, that still has its escaping backslashes) into native JavaScript object.

echo json_encode(["url" => "http://stackoverflow.com"]);
// {"url":"http:\/\/stackoverflow.com"}

// out of scope, but response is the response from your ajax call
var parsedJson = JSON.parse(response);
console.log(parsedJson.url);
// http://stackoverflow.com

This is how you actually get your unescaped string from JSON.

Quolonel Questions
  • 6,603
  • 2
  • 32
  • 33