Take the following PHP array:
$arr = array(
'about' => 'Ai você fala o seguinte: "- Mas vocês acabaram isso?" Vou te falar: -"Não, está em andamento!" Tem obras que "vai" durar pra depois de 2010. Agora, por isso, nós já não desenhamos, não começamos a fazer projeto do que nós "podêmo fazê"? 11, 12, 13, 14...',
'construction' => 100,
);
When parsed to JSON with PHP's json_encode, I get the following string:
[{"about": "Ai você fala o seguinte: \"- Mas vocês acabaram isso?\" Vou te falar: -\"Não, está em andamento!\" Tem obras que \"vai\" durar pra depois de 2010. Agora, por isso, nós já não desenhamos, não começamos a fazer projeto do que nós \"podêmo fazê\"? 11, 12, 13, 14...", "construction": 100}]
Note that the double quotes in the original string get escaped with a backslash. It looks good and even validates.
When I try to parse the JSON in Chrome or Safari (using JSON.parse()), I get the following error in the console:
Uncaught SyntaxError: Unexpected number
Firefox gives me:
SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 39 of the JSON data
From the Firefox error, I gather the first escaped double quote in the string seems to break the code.
If I manually escape the backslashes before the quotes, I get the expected object...
How can I prevent this error? Am I doing something wrong?
Relevant code:
Model:
// Returns an array with basic enterprise information
public function getBasicInfo($destination = null)
{
$response = array(
'id' => $this->id,
'name' => $this->name,
'category' => ! empty($this->category_id) ? $this->category->name : '',
'neighborhood' => ! empty($this->neighborhood) ? $this->neighborhood : '',
'city' => (! empty($this->city) ? $this->city : '') . (! empty($this->state_id) ? (! empty($this->city) ? ', ' : '') . $this->state->abbreviation : ''),
'dorms' => $this->dormitories_text,
'area' => $this->area,
'status' => ! empty($this->status_id) ? $this->status->name : '',
'price' => $this->price > 0 ? 'R$ ' . number_format($this->price, 2, ',', '.') : '',
'installment' => $this->installment > 0 ? 'R$ ' . number_format($this->installment, 2, ',', '.') : '',
'image' => ! empty($this->card_image_id) && is_object($this->card_image) ? $this->card_image->getUrl() : '',
'logo' => ! empty($this->logo_image_id) && is_object($this->logo_image) ? $this->logo_image->getUrl() : '',
'permalink' => $this->getPermalink($destination),
'about' => ! empty($this->about) ? $this->get_html($this->about) : '',
'construction' => $this->getLatestConstructionStageProgress(),
);
return $response;
}
Controller:
// Build data array
$json = array();
foreach ($enterprises as $enterprise) {
$json[] = $enterprise->getBasicInfo(REALTOR_URL);
}
$json = json_encode($json);
// Build data array
$data = array(
'urlOrigin' => $this->url_origin(),
'module' => 'Portal do Corretor - Empreendimentos',
'categories' => \Type::getByType('category'),
'cities' => \Enterprise::getUniqueCities(),
'statuses' => \Type::getByType('status'),
'prices' => \Enterprise::$priceRanges,
'installments' => \Enterprise::$installmentRanges,
'neighborhoods' => $neighborhoods,
'json' => $json,
'filters' => (object) array(
'search' => isset($_POST['search']) && ! empty($_POST['search']) ? $_POST['search'] : null,
'city' => isset($_POST['city']) && ! empty($_POST['city']) ? $_POST['city'] : null,
'neighborhood' => isset($_POST['neighborhood']) && ! empty($_POST['neighborhood']) ? $_POST['neighborhood'] : null,
'category' => isset($_POST['category']) && ! empty($_POST['category']) ? intval($_POST['category']) : null,
'dormitories' => isset($_POST['dormitories']) && ! empty($_POST['dormitories']) ? intval($_POST['dormitories']) : null,
'status' => isset($_POST['status']) && ! empty($_POST['status']) ? intval($_POST['status']) : null,
),
'sectionId' => 'empreendimentos',
);
// Merge default values with the data array
$data = array_merge($data, $this->getDefaultValues());
// Returns the view with the data array
return $this->view(REALTOR_URL . DS . 'empreendimentos', $data);
View:
<script type="text/javascript">
var enterprises = '<?php echo $json; ?>';
</script>
JavaScript:
if ($('#enterprises') && $('#enterprise-template').length && 'undefined' !== typeof enterprises) {
enterprises = JSON.parse(enterprises);
enterprisesCount = enterprises.length;
}
var foo = <?php echo $json ?>;. no need for dumping into a'string and then parsing separately. however, since your string is getting corrupted, it'd still get corruped this other way anyways - have you CONFIRMED that you have correct character sets everywhere? e.g. if you're building the json in a (say) win-1252 charset environment, then dumping into a utf-8 page, you'll get mangled characters.JSON.parse('[{"about": "Ai você fala o seguinte: \"- Mas vocês acabaram isso?\" Vou te falar: -\"Não, está em andamento!\" Tem obras que \"vai\" durar pra depois de 2010. Agora, por isso, nós já não desenhamos, não começamos a fazer projeto do que nós \"podêmo fazê\"? 11, 12, 13, 14...", "construction": 100}]');in your console? If you get the same error, we can rule out encoding issues.var foo = [{....}];would be perfectly acceptable/valid javascript.