json parse error with double quotes

前端 未结 9 1147
悲哀的现实
悲哀的现实 2020-12-01 11:38

A double quote even if escaped is throwing parse error.
look at the code below

//parse the json in javascript  
var testJson = \'{\"result\": [\"lunch\",         


        
相关标签:
9条回答
  • 2020-12-01 12:23

    Turn off magic_quotes_gpc in php.ini.

    0 讨论(0)
  • 2020-12-01 12:34

    If the standard C escapes are added, then JSON.parse will convert sequences like \" into ", \\ into \, \n into a line-feed, etc.

    'foo\\bar\nbaz"' === JSON.parse('"foo\\\\bar\\nbaz\\""')
    

    In our project's case:

    original string ""{\"lat\":28.4594965,\"lng\":77.0266383}""

    After passing to JSON.parse()

    "{"lat":28.4594965,"lng":77.0266383}"
    

    On 2nd pass to JSON.parse()

    {lat: 28.4594965, lng: 77.0266383}
    

    Notice that JSON.parse() removed escaping characters instead of converting string to object.

    After the escaping characters were removed, the string to object conversion worked.

    Here is the demo:

    while (typeof p1 != 'object') {
      p1 = JSON.parse(p1);
      pass++;
      console.log('On pass ', pass, p1);
    }
    
    0 讨论(0)
  • 2020-12-01 12:37

    Try This. and then try commented

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <pre><?php ($_POST)?print_r($_POST):'' ?></pre>
    
    <form method="POST">
        <input type="text" name="name"><br>
        <input type="email" name="email"><br>
        <input type="time" name="time"><br>
        <input type="date" name="date"><br>
        <input type="hidden" name="id"><br>
        <textarea name="detail"></textarea>
        <input type="submit" value="Submit"><br>
    </form>
    <?php 
    /* data */
    $data = [
                'name'=>'vinay"'."'\\\\",
                'email'=>'imvsrajput@demo.demo',
                'time'=>date('H:i:00'),
                'date'=>date('Y-m-d'),
                'detail'=>'Try this var_dump(0=="ZERO") \\ \\"'." ' \\\\    ",
                'id'=>123,
            ];
    ?>
    <span style="display: none;" class="ajax-data"><?=json_encode($data)?></span>
    <script type="text/javascript">
        /* Error */
        // var json = JSON.parse('<?=json_encode($data)?>');
        /* Error solved */
        var json = JSON.parse($('.ajax-data').html());
        console.log(json)
        /* automatically assigned value by name attr */
        for(x in json){
            $('[name="'+x+'"]').val(json[x]);
        }
    </script>
    
    0 讨论(0)
提交回复
热议问题