Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Uncaught SyntaxError: Unexpected token x in JSON at position 1' when trying to parse HTML embeded string JSON

I've being trying to parse a hardcoded JSON string to an usable format, but I can't find a way to get it work, getting 'Unexpected token' or just weird outputs. Library used: jQuery. The data to be stored is:

x:10
y,10

and

x:200
y:10

It's stored in a data attribute called data-pos, and I've tried multiple solutions, listed below:

  • Token error results (all combinations):

Used functions

JSON.parse(data);
$.parseJSON(data);
jQuery.parseJSON(data);

Data formats

data-pos="{'x':10,'y':10}"
data-pos="{'x':'10','y':'10}"
data-pos="{x:'10',y:'10'}"
data-pos="{x:10,y:10}"
  • Just weird output (no parsing):

Used functions

alert(data);
    --> output: 
        !!DATA AS IS!!
        !!DATA AS IS!!

alert ('x: ' + data.x + ' y: ' + data.y); /* Using {x: 200, y: 10} format */
    --> outputs:
        x: undefined y: undefined
        x: {y'    <-- Yep, THIS. No typos. IDK what the hell is going on.

Data formats

data-pos="{'x':10,'y':10}"
data-pos="{'x':'10','y':'10}"
data-pos="{x:'10',y:'10'}"
data-pos="{x:10,y:10}"

Sourcefile:

<html>    
    <head>
        <script>var devmode = true</script>
        <script>var loadExec=false</script>
        <script src="/files/js/jquery.min.js"></script>
    </head>
    <body id="body" class="selectable nooverflow">
        <div class="container hidden desktop">
            <div class="window selectable"  data-pos=!!DATA!!>
                <div class="titlebar">
                    <span class="titletext" onmousedown="movingW=true" onmouseup="movingW=false">Window 1</span>
                </div>
            </div>
            <div class="window" data-pos=!!DATA!!> 
                <div class="titlebar">
                    <span class="titletext" onmousedown="movingW=true" onmouseup="movingW=false">Window 2</span>
                </div>
            </div>
        </div>
        <link rel="stylesheet" type="text/css" href="/files/css/style.css">
        <script src="/files/js/core.js"></script>       <!-- irrelevant -->
        <script src="/files/js/subcore.js"></script>    <!-- irrelevant -->
        <script>        
            $(function () {
                $(window).on("load", function () {
                    $('.window').each(function (index) {
                        if (!loadExec) {
                            var data = $(this).data('pos');
                            //alert(data + "\nDatatype: " + (typeof data));
                            if (data) {
                                alert(data);

                                //PARSING HERE!! <----------

                                $(this).css({ 'top': data.y, 'left': data.x, position: 'absolute' });
                            }

                            loadExec = true;
                            $('.container').removeClass('hidden');
                        }
                    });
                });
            });
        </script>
    </body>
</html>

I've been searching but all I could find was unsuccesfull or ajax orientated. I just need to embed this JSON string in an attribute or some inside-DOM way. I just can't find the solution.

THANKS FOR YOUR TIME!

like image 304
Akryllax Avatar asked May 27 '16 10:05

Akryllax


People also ask

How do I fix unexpected token in JSON at position?

The "Unexpected token u in JSON at position 0" error occurs when we pass an undefined value to the JSON. parse or $. parseJSON methods. To solve the error, inspect the value you're trying to parse and make sure it's a valid JSON string before parsing it.

How do I fix SyntaxError JSON parse unexpected character at line 1 column 1 of the JSON data?

The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.

How do you handle JSON parsing error?

The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.


1 Answers

In JSON, quotes must be double quotes, and all property names must be strings (e.g., in quotes), so none of the data formats you listed is correct. This would be correct:

data-pos='{"x":10,"y":10}'

or if it's important to put the attribute value in double quotes, since the content of attributes is HTML text (something people tend to forget), you could use &quot;:

data-pos="{&quot;x&quot;:10,&quot;y&quot;:10}"

...but only do that if you absolutely have to use " instead of ' around the attribute value.

For details about JSON, including the fact that strings and property names must be in double quotes, refer to the JSON website.

Examples:

console.log("a's data:", $("#a").data("pos"));
console.log("b's data:", $("#b").data("pos"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="a" data-pos='{"x":10,"y":10}'></div>
<div id="b" data-pos="{&quot;x&quot;:10,&quot;y&quot;:10}"></div>
like image 125
T.J. Crowder Avatar answered Sep 20 '22 23:09

T.J. Crowder