0

I've looked at several examples, all over, and in my opinion this is valid, but when I load JSON as a script file, e.g:

<script src="../js/side-menu.json"></script>

Chrome gives me the error:

SyntaxError: Unexpected token :

That is the : at the end of "side-menu":. This is the JSON:

{
  "side-menu": {
    "sections": [
      {
        "dashboard": [
          {
            "title": "Firewall",
            "url": "dashboard_2.html",
            "icon": "icon-bulb",
            "menuVisual": "selected"
          }
        ]}
    ]}
}

Is this perhaps because the browser is interpreting the file as JavaScript instead?

ProfK
  • 49,207
  • 121
  • 399
  • 775

4 Answers4

2

json looks fine for me as well. Check this issue, it seems related

HTML/Javascript: how to access JSON data loaded in a script tag with src set

Community
  • 1
  • 1
SCouto
  • 7,808
  • 5
  • 32
  • 49
1

The JS parser confuses the curly braces with a code block instead of an object literal. You can avoid this by putting it into parentheses like this ({...}).

Your file won't be JSON anymore if you do this. How exactly this followup problem can be fixed depends, but you'll have to think about something different first: What exactly do you expect from including a file that contains only JSON? After all, this JSON won't be available in a variable if you do that, since there's only the JSON value, no assignment to a variable.

Martin Geisse
  • 1,189
  • 1
  • 9
  • 22
0

Am not sure what you are trying to achieve doing this.

<script src="../js/side-menu.json"></script>

This is going to get your json and interpret it as javascript.

Maybe what you are looking for is.

 <script language="javascript">`
 var my_json = {
  "side-menu": {
    "sections": [
      {
        "dashboard": [
          {
            "title": "Firewall",
            "url": "dashboard_2.html",
            "icon": "icon-bulb",
            "menuVisual": "selected"
          }
        ]}
    ]}
};
</script>

inside the <script> tag.

phreakv6
  • 2,135
  • 1
  • 9
  • 11
0

The issue here is that your are trying to load pure JSON using the Script tag which is by default looking for plain old script code. You have two one options here -

  1. Specify type="application/json" in the script tag, also give it an id. Then wherever in you need to access the data, find the script element using its id and do JSON.parse($("#scriptelementid").html());. Replace jQuery with plain javascript if you ain't using it.

  2. OR, change your json content to this -

    var exportedData = {
      "side-menu": {
        "sections": [
          {
            "dashboard": [
              {
                "title": "Firewall",
                "url": "dashboard_2.html",
                "icon": "icon-bulb",
                "menuVisual": "selected"
              }
            ]}
        ]}
    };
    
hazardous
  • 10,627
  • 2
  • 40
  • 52