I'm pulling rows that contain JSON content from a DB like this:
<?php
//get the data from the database
global $wpdb;
$current_user = wp_get_current_user();
$username = $current_user->user_login;
$rowResults = $wpdb->get_results( "SELECT username, myJson FROM jsonData WHERE username = '$username'" );
?>
Then I'm trying to deconstruct the JSON back into a javascript object:
<?php echo $i ?>
<?php echo $result->username; ?>
<script>
let itemFromDB = <?php echo $result->myJson; ?>;
let parsedItem = JSON.parse(itemFromDB);
doSomething(parsedItem); //use the js object
</script>
<?php $i++ ?>
<br>
<?php } ?>
The problem is that itemFromDB will contain a string that has escape characters everywhere like this:
{\"someData\":\"qwe\",\"moreData\":\"2\",\"tags\":\"dffdf\",\"evenMore\":\"30\",\"anotherOne\":\"1\",\"moreandmore\":[{\"something\":\"w\",\"amount\":\"1};
I tried to write:
let itemFromDB = <?php echo json_decode($result->myJson); ?>;
But that just resulted in an empty string.
How can I remove the escape characters and convert my query result into a javascript object?
I'm pulling rows that contain JSON content from a DB like this:
<?php
//get the data from the database
global $wpdb;
$current_user = wp_get_current_user();
$username = $current_user->user_login;
$rowResults = $wpdb->get_results( "SELECT username, myJson FROM jsonData WHERE username = '$username'" );
?>
Then I'm trying to deconstruct the JSON back into a javascript object:
<?php echo $i ?>
<?php echo $result->username; ?>
<script>
let itemFromDB = <?php echo $result->myJson; ?>;
let parsedItem = JSON.parse(itemFromDB);
doSomething(parsedItem); //use the js object
</script>
<?php $i++ ?>
<br>
<?php } ?>
The problem is that itemFromDB will contain a string that has escape characters everywhere like this:
{\"someData\":\"qwe\",\"moreData\":\"2\",\"tags\":\"dffdf\",\"evenMore\":\"30\",\"anotherOne\":\"1\",\"moreandmore\":[{\"something\":\"w\",\"amount\":\"1};
I tried to write:
let itemFromDB = <?php echo json_decode($result->myJson); ?>;
But that just resulted in an empty string.
How can I remove the escape characters and convert my query result into a javascript object?
Share Improve this question asked Apr 22, 2020 at 18:36 AnttiAntti 1272 silver badges7 bronze badges1 Answer
Reset to default 0You probably need to decode JSON string to use in the JS code, so something like
let parsedItem = <?php echo stripslashes($result->myJson); ?>;
Note that you will get JSON object, so no need to call JSON.parse there. I added stripslashes to remove extra \" from json string loaded from database.