简体   繁体   中英

How to encode json and special characters from php to javascript?

In my db I save the json in a custom field called usp-custom-12 like this:

[{"Mamma":["Papa"]}]

Then I try to decode that

<?php
  $jsonTable = usp_get_meta(false, 'usp-custom-12');
?>
var data = <?php echo htmlspecialchars_decode($jsonTable); ?>;

But it is giving me

 var data = "[{"Mamma":["Papa"]}]";

And a console log error:

Uncaught SyntaxError: Unexpected identifier

The full code:

<?php
  $jsonTable = usp_get_meta(false, 'usp-custom-12');
?>
var data = "<?php echo htmlspecialchars_decode($jsonTable); ?>";

console.log(data);

data = JSON.parse (data);
data.forEach(obj => {
  Object.keys(obj).forEach(key => {
    $('#newTable thead tr').append($('<th>').text(key));

    obj[key].forEach((e, i) => {
      if(!$("#newTable tbody tr:eq("+i+")").length) $("<tr>").appendTo($("#newTable tbody"));
      $("#newTable tbody tr:eq(" + i + ")").append($('<td>').text(e))
    })
  })
});

In this jsFiddle if you click save table you will see it generates a table identical to the top one, that's also logging in console the correct json: https://jsfiddle.net/fbh0o67o/74/

$jsonTable contains a JSON string with html entities encoded, since it's already JSON, you just have to decode the html etities and echo it as is. No JSON decoding is required, no quoting is required. Just HTML decode and echo it into your javascript.

var data = <?php echo htmlspecialchars_decode(usp_get_meta(false, 'usp-custom-12')); ?>;

data.forEach(obj => {
   // Loop stuff here...
});

The issue is with the quotes inside the string "mama" you need to escape those quotes using addslashes method.

Try using the following:

var data = "<?php echo addslashes(htmlspecialchars_decode($jsonTable)); ?>";

JSON to PHP:

json_decode($string);

If you use the optional parameter $assoc as true - json_decode($string, true) will return associative array on success.

PHP to JSON:

json_encode($array);

PHP manuals: json_encode() json_decode()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM