简体   繁体   中英

Not able to read JSON file

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"}]};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM