jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

后端 未结 7 1062
挽巷
挽巷 2020-11-22 14:04

I’m making requests to my server using jQuery.post() and my server is returning JSON objects (like { \"var\": \"value\", ... }). However, if any of

7条回答
  •  佛祖请我去吃肉
    2020-11-22 14:41

    I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.

    I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.

    Could it be a mistake in my implementation that looks like this (PHP - server side):

    $data = array();
    
    $elem = array();
    $elem['name'] = 'Erik';
    $elem['position'] = 'PHP Programmer';
    $data[] = json_encode($elem);
    
    $elem = array();
    $elem['name'] = 'Carl';
    $elem['position'] = 'C Programmer';
    $data[] = json_encode($elem);
    
    $jsonString = "[" . implode(", ", $data) . "]";
    

    The final step is that I store the JSON encoded string into an JS variable:

    
    

    If I use "" instead of '' it still throws an error.

    SOLUTION:

    The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:

    json_encode($tmp, JSON_HEX_APOS);
    

    Is there another way of tackle this issue? Is my code wrong or poorly written?

    Thanks

提交回复
热议问题