0

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?

0

You 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.

3
  • With that I'm getting this error: Recoverable fatal error: Object of class stdClass could not be converted to string
    – Antti
    Apr 22 '20 at 19:20
  • just drop json_decode - what was I thinking :D Keep stripslashes - that will remove slashes and just echo it. Your parsed item will be JSON object (so no need to parse it);
    – Worduoso
    Apr 22 '20 at 21:18
  • It worked, thank you so much!
    – Antti
    Apr 23 '20 at 3:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.