Zhang Quan
Zhang Quan

Reputation: 77

Google Apps Script JSON can't be parsed on client-side

I'm having issues parsing my JSON data in Apps Script. On my client side HTML, I'm looping the data I've pulled to create several divs. I have a "toggleVideo" function on my client side which is meant to log the "data" attribute stored.

HTML:

<? for (let i =0; i<videos.length; i++){ ?>
<div onClick="toggleVideo(this)" data='<?!= JSON.stringify(videos[i])  ?>' class="col video-preview-container">
    <div class="video-preview-image" style="background-image: url(<?= videos[i].preview_url ?>);"></div>
    <div class="video-preview-title-speaker-container">
        <div class="video-preview-title"><?= videos[i].title ?></div>
        <div class="video-preview-speaker"><?= videos[i].speaker ?></div>
    </div>
</div>
<? } ?>

toggleVideo function to get data stored in the div:

function toggleVideo(param) {
    var videoData = param.getAttribute("data");
    var videoDataParsed = `'${videoData}'`;
    videoDataParsed.replace(/\\n/g, "\\n")
        .replace(/\\'/g, "\\'")
        .replace(/\\"/g, '\\"')
        .replace(/\\&/g, "\\&")
        .replace(/\\r/g, "\\r")
        .replace(/\\t/g, "\\t")
        .replace(/\\b/g, "\\b")
        .replace(/\\f/g, "\\f");
    console.log(JSON.parse(videoDataParsed));
}

When I console.log the data when it isn't parsed, there's no issue at all, it returns me a string with the data. I tried using JSON.parse() in my browser console, adding '' before and after the {}, and it parsed perfectly fine and returns the object. But when I add I try to parse it within the toggleVideo function, it returns the following error:

VM38:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse () at toggleVideo (userCodeAppPanel:30) at HTMLDivElement.onclick (userCodeAppPanel:1)

I've tried adding the replace(/\...etc. to get rid of any invisible characters, but it still doesn't work. Anyone knows what might be the issue?

Upvotes: 0

Views: 494

Answers (1)

Dmitry Kostyuk
Dmitry Kostyuk

Reputation: 1459

The error you are getting means that JSON.parse() doesn't like the datatype that it sees, meaning you are probably not passing a string representing an proper JSON object.

Your issue is coming from this line:

var videoDataParsed = `'${videoData}'`;

You are trying to convert an object to a string here, but this doesn't convert properly, for instance it doesn't handle the quotation marks " properly.

If you have an object, you want to replace it with the following:

var videoDataParsed = JSON.stringify(videoData);

But it looks like you already have a string, so your additional conversion simply violates the JSON format. So if you just delete the line in question, you'll be fine.

Upvotes: 1

Related Questions