简体   繁体   中英

remove double quotes from json encoded array

   $SQL = "SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'mst_sim_data' 
            AND COLUMN_NAME = 'status'";
   $result = mysql_query($SQL);
   $row = mysql_fetch_array($result);
   $enumList = explode(",", str_replace("'", '', substr($row['COLUMN_TYPE'], 5,     (strlen($row['COLUMN_TYPE'])-6))));

    foreach ($enumList as $key => $value) {
        $list["'$value'"] = $value;
    }       
    return json_encode($list);  

This returns following json string.

Object {'INSTOCK': "INSTOCK", 'ISSUED': "ISSUED", 'SOLDOUT': "SOLDOUT"}

But I need to replace single quotes over double quotes and it should be like this,

'INSTOCK': 'INSTOCK', 'ISSUED': 'ISSUED', 'SOLDOUT': 'SOLDOUT'}

How can I do this?

Is the goal to break JSON output? JSON strings and properties must use " as the quote.

I believe the problem is two fold

  1. $list["'$value'"] = $value; should be $list["$value"] = $value; and

  2. the " s should be left alone


If you do wish to mangle the quotes (which means the result is not JSON), then use the result of

str_replace('"', "'", json_encode($list, JSON_HEX_APOS))

Note the JSON_HEX_APOS flag, to prevent this gross hack from mutilating any JSON-string embedded ' characters.

$SQL = "SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_NAME = 'mst_sim_data' 
            AND COLUMN_NAME = 'status'";
   $result = mysql_query($SQL);
   $row = mysql_fetch_array($result);
   $enumList = explode(",", str_replace("'", '', substr($row['COLUMN_TYPE'], 5,     (strlen($row['COLUMN_TYPE'])-6))));

    foreach ($enumList as $key => $value) {
        $list["$value"] = $value;
    }       
    return str_replace('"',"'",json_encode($list));

and then on js I again encoded the array

       <?php 
          $this->load->module('sim/sim');
          $enumList = $this->sim->status_enum_dropdown();
      ?>  

        <script type="text/javascript">
            var enumList = <?php echo json_encode($enumList); ?>;
        </script>

Now it works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM