0

How could I get access to json from another file?

I tried:

obdatabase.json

   { "pobject" :[
    { "pname":"Pikachu" , "pid":"1" },
    { "pname":"squirtle" , "pid":"2" },
    { "pname":"Justinbieber" , "pid":"3" }
    ]};

test.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="obdatabase.json"></script>
<script>
$(function() {
    console.log(pobject);
});
</script>
IsraGab
  • 4,819
  • 3
  • 27
  • 46
ryanpika
  • 151
  • 3
  • 13
  • Possible duplicate of [HTML/Javascript: how to access JSON data loaded in a script tag with src set](http://stackoverflow.com/questions/13515141/html-javascript-how-to-access-json-data-loaded-in-a-script-tag-with-src-set) – Arman Ozak Feb 14 '16 at 22:03

1 Answers1

2

Use jQuery's getJSON() method:

var obj = $.getJSON( 'obdatabase.json' );

Since getJSON will automatically parse the result into a Javascript object, you may access the properties as follows:

// Get the object:
var db;

$.getJSON( 'obdatabase.json', function(obj) {  
    // Now we can access properties:
    obj.pobject[0].pname; // Will be Pikachu

    // Assign obj to db (so we can access it outside of the callback):
    db = obj;
});
BenM
  • 52,573
  • 26
  • 113
  • 168
  • it prints error Unexpected token : of my obdatabase.json. What's wrong with my json file? Could you help me to test it thanks! – ryanpika Feb 14 '16 at 22:01
  • Try removing the semicolon at the end of your JSON file. – BenM Feb 14 '16 at 22:03
  • It still prints the same error. Could you test again, thanks! – ryanpika Feb 14 '16 at 22:10
  • There's nothing wrong with your JSON structure as posted (sans trailing semicolon). This works OK when I tried it. Try removing excess whitespace and newlines from your JSON file. – BenM Feb 14 '16 at 22:11
  • Need to use `done` callback ... ajax is asynchronous and `obj` is a promise not the data – charlietfl Feb 14 '16 at 22:15
  • @charlietfl. Could you write some code to show how to access the data? Many thanks, I'm kind of new to this stuff. – ryanpika Feb 14 '16 at 22:17
  • @BenM Cool! I can have access to pikachu now. But there has a serious inconvenience since I can't get access to the obj outside of this function. Any idea to resolve this? – ryanpika Feb 14 '16 at 22:22
  • Assign it to a wider-scoped variable. See the edited answer; be mindful that you'll need to wait for the AJAX request to complete, though, so accessing it inside the callback is your safest bet. – BenM Feb 14 '16 at 22:24
  • As I said, this does work. But probably you're trying to access properties of db before the AJAX request has completed. This is why you need to access it inside the callback. – BenM Feb 14 '16 at 22:38
  • @BenM just did, sorry forgot – ryanpika Feb 20 '16 at 05:03