PHP/JSON - Remove every occurence of certain character before another character

大兔子大兔子 提交于 2019-12-12 02:55:00

问题


My JSON is encoding peculiarly, so I need to remove every quote before a right-opening bracket. (e.g. every " before a {) Is it possible to do this in PHP, and if so, how?

"{ I would want to remove every occurrence of the quote before the bracket.

JSON here: http://devticker.pw/json-data.php

Code here:

while($row = mysqli_fetch_array($result))
{
$data[] = '{"c": [{ "v": ' . $row['Timestamp'] . '"},{"v":' . $row['USD'] . '} ]}';
}

$str = json_encode(array("rows"=>$data));

$str = substr($str, 1);

$str = str_replace("\"{", "{", $str);

$str = '{"cols":[{"type":"string"},{"type":"number"}],' . $str;

$str = stripslashes($str);

echo $str;

回答1:


The problem is you are generating part of the JSON manually and then encoding that string with json_encode, which is escaping the quotes that should not be escaped. This is wrong. Using str_replace to remove the escaping is a workarround, not the correct way to generate your JSON.

If you generate your JSON using only json_encode it works well. Something like this should work:

// your columns
$cols = array();
$cols[0] = array('type' => 'string');
$cols[1] = array('type' => 'number');

// your rows
$rows = array();

while ($row = mysqli_fetch_array($result)) {
    $r = new stdClass();
    $r->c = array();

    $r->c[0] = array('v' => $row['Timestamp']);
    $r->c[1] = array('v' => $row['USD']);

    $rows[] = $r;
}

// the final result
$result = array(
    'cols' => $cols,
    'rows' => $rows
);

// don't forget this
header('Content-Type: application/json');

echo json_encode($result);



回答2:


Try

while($row = mysqli_fetch_array($result))
{
    $data[] = array("c" => array(array( "v" => $row['Timestamp']), array("v" => $row['USD'] ))));
}

$rows = array("rows"=>$data));

$cols = array("cols" => array(array("type"=>"string"),array("type"=>"number")),$row);

$str = json_encode($cols);

echo $str;



回答3:


Really can't understand why you need to do this (and why you are manupulating raw JSON string), but you can simply use the string-replacement function of php, str_replace:

$your_json_string = str_replace("\"{", "{", $your_json_string);



回答4:


What version of PHP are you using?

If 5.3 or greater than you can use this:

return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);

Frameworks like drupal have handled this stuff - you could probably rip some code from here to roll your own json_encode function https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_json_encode/7




回答5:


$json = str_replace('"{','{',$json) 


来源:https://stackoverflow.com/questions/20734771/php-json-remove-every-occurence-of-certain-character-before-another-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!