php json_encode & jquery parseJSON single quote issue

后端 未结 5 2048
庸人自扰
庸人自扰 2020-12-24 01:40

I searched and read most of the related topics, but they weren\'t what I was looking for.

I\'ve a JSON enocded string with json_encode PHP function:

相关标签:
5条回答
  • 2020-12-24 01:47

    For the broader problem of passing a JSON-encoded string in PHP (e.g., through cURL), using the JSON_HEX_APOS option is the cleanest way to solve this problem. This would solve your problem as well, although the previous answers are correct that you don't need to call parseJSON, and the JavaScript object is the same without calling parseJSON on $data.

    For your code, you would just make this change:

    json_encode($var) to json_encode($var, JSON_HEX_APOS).

    Here's an example of the correctly encoded data being parsed by jQuery: http://jsfiddle.net/SuttX/

    For further reading, here's an example from the PHP.net json_encode manual entry Example #2:

    $a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");
    
    echo "Apos: ",    json_encode($a, JSON_HEX_APOS), "\n";
    

    This will output:

    Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
    

    A full list of JSON constants can be found here: PHP.net JSON constants

    0 讨论(0)
  • 2020-12-24 01:52

    The issue you are facing is that you are presenting the results of the json_encode call to JavaScript as a string whereas it is valid JavaScript. Remove the jQuery.jsonParse set out of the output and simply assign the echoed results to the JavaScript variable in question.

    var obj = <?= json_encode(array("casts"=>array(
        "Matthew Modine","Adam Baldwin","Vincent D'Onofrio"
    ),"year"=>1987)); ?>;
    
    0 讨论(0)
  • 2020-12-24 02:00

    However when I make a change in JSON encoded string - adding Backslash to single quote

    That escapes it in the PHP string literal. It is then inserted into the PHP string as a simple '.

    If you want to escape it before inserting it into JavaScript then you need to add slashes to the string you get out of json_encode (or rather, since you aren't using that (you should be!) the JSON string you build by hand).

    That is more work then you need though. The real solution is to remember that JSON is a subset of JavaScript literal syntax:

    var obj = <?=$data?>;
    
    0 讨论(0)
  • 2020-12-24 02:00

    This should be straightforward if the issue is about single quote only:

    str_replace("'", "\'", json_encode($array));
    
    0 讨论(0)
  • check out its really help me

    $products_arr=array();
    $products_arr["category"]=array();
     while ($row = $cats->fetch(PDO::FETCH_ASSOC)){
    
        $product_item=array(
            "id" => $row['id'],
            "title" => json_encode($row['title'])// these will help you
        );
    
        array_push($products_arr["category"], $product_item);
    }
    
    echo json_encode($products_arr);
    
    0 讨论(0)
提交回复
热议问题