David Lerner
David Lerner

Reputation: 651

Target inline JSON using jQuery .getJSON or similar method

I am attempting to get data from an inline array wrapped in a <script> tag using jQuery's .getJSON method. As far as I am reading in documentation (http://api.jquery.com/jquery.getjson/), .getJSON requires a URL and external file to call from.

$.getJSON('items.js', function(data) {});

How would I use either this method or another one to specifically target an inline array (without an external file), such as the one below:

  <script type="application/json">   
   {
    "items": {
        "blue": {
          "a": "a",
          "b": "b",
          "c": "c"
        }
     }
   }
  </script>

Thanks!

Upvotes: 1

Views: 1000

Answers (2)

Barmar
Barmar

Reputation: 782005

You can't put JSON by itself in a script tag, it has to be valid Javascript statements. Assign the JSON to a variable name:

<script>
var data = {
    "items": {
        "blue": {
          "a": "a",
          "b": "b",
          "c": "c"
        }
     }
};
<script>

Then the rest of your code can use data to access the value.

Upvotes: 3

Cameron
Cameron

Reputation: 1524

It's better to store this data into a JavaScript object.

Do something like this:

<script type="text/javascript">
    var jsonData = <?php echo json_encode($dataArray, JSON_HEX_TAG);?>;
</script>

Upvotes: 1

Related Questions