Home > Blockchain >  HTML doesn't accept colon(:) inside json
HTML doesn't accept colon(:) inside json

Time:11-15

My json file looks like this:

{
    "data": {
        "test":"0123"
    }
}

And I get this error: Uncaught SyntaxError: Unexpected token ':'

enter image description here

Why does this happen and how can I fix the problem?

Edit: the HTML code

<html>
    <body>
        <button id="clickThis" onclick="change()">
            Text here
        </button>
        
        <script type="text/javascript" src="./lista.json">
            function change() {
                var mydata = JSON.parse(data)
                document.getElementById("clickThis").innerHTML = "this"
            }
        </script>
    </body>
</html>
<html>
    <body>
        <button id="clickThis">
            Text here
        </button>
        <script src="./lista.json">
        </script>
    </body>
</html>

CodePudding user response:

Try making your data object an array-of-objects. I'd assume you'd eventually have more than 1 data:

{
    "data": [
        {
            "test": "0123"
        }
    ]
}

CodePudding user response:

Name your JSON file correct: lista.json

CodePudding user response:

You have a "naked" json object, the snippet below illustrates the problem

{
    "data": {
        "test":"0123"
    }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Either assign it to a variable

data = {/*OBJECTS*/}

and use it natively, or encapsulate it in a string and parse it. I'd assign it to an object

var v = {
    "data": {
        "test":"0123"
    }
}

console.log(v.data);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related