最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Not able to read JSON file - Stack Overflow

programmeradmin0浏览0评论

I have following code for reading a JSON file.It is giving no error but i am getting null in the variable:

var myData = null;
$.ajax({
    type: 'GET',
    async: false,
    url: 'myJson.json',
    dataType: 'json',
    success: function (r) {
        myData = r;
    }
});

Below is my JSON file:

{items:[{value:"1",name:"John"},{value:"2",name:"Henry"}]};

I have following code for reading a JSON file.It is giving no error but i am getting null in the variable:

var myData = null;
$.ajax({
    type: 'GET',
    async: false,
    url: 'myJson.json',
    dataType: 'json',
    success: function (r) {
        myData = r;
    }
});

Below is my JSON file:

{items:[{value:"1",name:"John"},{value:"2",name:"Henry"}]};
Share Improve this question edited May 23, 2013 at 5:23 Mr_Green 41.9k47 gold badges170 silver badges276 bronze badges asked May 23, 2013 at 5:03 Aquarius24Aquarius24 1,8646 gold badges34 silver badges62 bronze badges 4
  • 3 Why not use $.getJSON instead? – Marty Commented May 23, 2013 at 5:05
  • i tried without semicolon also – Aquarius24 Commented May 23, 2013 at 5:12
  • check here for valid or not – M.I.T. Commented May 23, 2013 at 5:12
  • 1 async : true.. ajax call should be asynchronous always. and your json is wrong as mentioned by benjamin in below post. Try jsonLint to test whether your json is in correct format or not, always. – Mr_Green Commented May 23, 2013 at 5:27
Add a ment  | 

1 Answer 1

Reset to default 13

Your JSON is invalid.

An object serialized in JSON is in the following format:

Where string is:

JSON strings must be escaped. You're missing the "s.

A correct JSON would be:

{"items":[{"value":"1","name":"John"},{"value":"2","name":"Henry"}]}

How I created it

Even if I hadn't remembered or looked up the specific JSON rules, you can always produce the JSON from the JS variable assuming it's serializable (in your case it is) by:

  • Open a JavaScript console
  • Type var a = and paste your object literal
  • Press enter.
  • Type JSON.stringify(a);
  • Press enter. Copy the result.
  • Paste the result in your external .json file. JavaScript's JSON.stringify produces valid JSON.
发布评论

评论列表(0)

  1. 暂无评论