1

i have an json array and i want to parse it in java-script but my jquery gives me following error:

JSON.parse: unexpected character 

The code in jquery is,on which the error comes:

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {//error comes on this line.
return window.JSON.parse( data );
} 

My code is:

success: function(msg){
                var test= JSON.parse(msg);
                var question=test.question;
        document.getElementById('question').value=question;

I am using the latest version of jquery

 <script src="http://code.jquery.com/jquery-latest.js"></script>

I am getting this in function(msg):

[Object { question=

"What is your religious affiliation?"

,  userQuestionCategoryId=

"1"

}]

Here is my Php code:

function getquest()
        {
             $id=$this->input->post('qid');
             $data=$this->adminsetting->getquestion($id);
             if(count($data)>0)
             //echo $data[0]->question; 
             echo json_encode($data);
             else
             echo "No Question In database";
        }

Thanks in advance.

Harshal
  • 3,562
  • 9
  • 36
  • 65
  • I guess it depends on the data you parse. Have a look to http://stackoverflow.com/questions/8524933/json-parse-unexpected-character-error. You don't need jQuery as well, to use JSON.parse – Alberto Arena Nov 05 '12 at 11:54
  • Do you have an example of the json you're trying to parse? – Lloyd Nov 05 '12 at 11:54
  • consoe.log(msg) and see the result , and please add your php code – Kanishka Panamaldeniya Nov 05 '12 at 11:56
  • 1
    FYI: jQuery uses the internal JSON parser if available [(source)](http://jsapi.info/jquery/1.8.0/jQuery.parseJSON) so you can just use `$.parseJSON()` – Andreas Nov 05 '12 at 11:58
  • @Andreas ,so am i doing wrong in my php code??i am using json_encode($data).is there any other way to do it?? – Harshal Nov 05 '12 at 12:03
  • Forget my last (deleted) comment... It looks like `msg` is already a parsed JSON string. Did you try `msg[0].question` ? – Andreas Nov 05 '12 at 12:09
  • ohhh...yes you are right,msg[0].question works..:( Thanks Andreas – Harshal Nov 05 '12 at 12:25

2 Answers2

1

This:

{ question=

"What is your religious affiliation?"

,  userQuestionCategoryId=

"1"

}

Must be like this:

{"question":"What is your religious affiliation?",  "userQuestionCategoryId":"1"}
Itsmeromka
  • 3,621
  • 9
  • 46
  • 79
1

Actually the json i s becomes alredy parsed so i have to just used the index,i am missing to use the index msg[0]. Thats why I am getting problem.

success: function(msg){



        document.getElementById('question').value=msg[0].question;

        document.getElementById('id').value=msg[0].userQuestionCategoryId;
        //alert(msg);
        } }); 
Harshal
  • 3,562
  • 9
  • 36
  • 65