how to use JSON.stringify and json_decode() properly

后端 未结 7 1670
野性不改
野性不改 2020-12-08 06:08

Im trying to pass a mulitidimensional Javascript array to another page on my site by:

  • using JSON.stringify on the array

  • assigning the result

相关标签:
7条回答
  • 2020-12-08 06:45

    When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.

    json_decode( html_entity_decode( stripslashes ($jsonString ) ) );
    

    Thanks to @Thisguyhastwothumbs

    0 讨论(0)
  • 2020-12-08 06:48

    You'll need to check the contents of $_POST["JSONfullInfoArray"]. If something doesn't parse json_decode will just return null. This isn't very helpful so when null is returned you should check json_last_error() to get more info on what went wrong.

    0 讨论(0)
  • 2020-12-08 06:52
    stripslashes(htmlspecialchars(JSON_DATA))
    
    0 讨论(0)
  • 2020-12-08 06:53

    None of the other answers worked in my case, most likely because the JSON array contained special characters. What fixed it for me:

    Javascript (added encodeURIComponent)

    var JSONstr = encodeURIComponent(JSON.stringify(fullInfoArray));
    document.getElementById('JSONfullInfoArray').value = JSONstr;
    

    PHP (unchanged from the question)

    $data = json_decode($_POST["JSONfullInfoArray"]);
    var_dump($data);
    
    echo($_POST["JSONfullInfoArray"]);
    

    Both echo and var_dump have been verified to work fine on a sample of more than 2000 user-entered datasets that included a URL field and a long text field, and that were returning NULL on var_dump for a subset that included URLs with the characters ?&#.

    0 讨论(0)
  • 2020-12-08 06:56

    When you use JSON stringify then use html_entity_decode first before json_decode.

    $tempData = html_entity_decode($tempData);
    $cleanData = json_decode($tempData);
    
    0 讨论(0)
  • 2020-12-08 07:00
    jsonText = $_REQUEST['myJSON'];
    
    $decodedText = html_entity_decode($jsonText);
    
    $myArray = json_decode($decodedText, true);`
    
    0 讨论(0)
提交回复
热议问题