使用PHP的json_encode创建的JSON导致解析错误

时间:2015-07-28 14:09:48

标签: php json

采用以下PHP数组:

$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,
);

当使用PHP json_encode解析为JSON时,我得到以下字符串:

[{"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}]

请注意,原始字符串中的双引号会以反斜杠进行转义。它看起来很好,甚至是validates

当我尝试在Chrome或Safari中解析JSON时(使用JSON.parse()),我在控制台中收到以下错误:

Uncaught SyntaxError: Unexpected number

Firefox给了我:

SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 39 of the JSON data

从Firefox错误中,我收集字符串中的第一个转义双引号似乎打破了代码。

如果我在引号前手动转义反斜杠,我会得到预期的对象......

如何防止此错误?我做错了吗?

相关代码:

型号:

// 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;
}

控制器:

    // 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);

查看:

<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;
}

2 个答案:

答案 0 :(得分:4)

你没有做任何“错误”。事实上,您已经自己找到了解决方案! PHP生成的字符串可能由echo传递给JavaScript - 使用类似

的内容将其转换为JavasScript代码行
var jsvar='<?= json_encode($arr) ?>';

结果看起来或多或少与您在帖子中显示的结果相同:

var js_var='[{"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}]';

当JavaScript解析此字符串时,\之前的"将被“吃掉”,而JSON.parse要解析的JSON字符串将如下所示:

'{"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}'

此字符串可以理解导致错误消息。

<强>解决方案:

所以,你需要做的是用\掩盖你所有的addslashes()

var jsvar='<?= addslashes(json_encode($arr)) ?>';
var o=JSON.parse(jsvar);

或者,正如@JAAulde非常正确地发布:你可以直接跳过变量的`string'状态:

var o=<?= json_encode($arr)) ?>;

答案 1 :(得分:2)

因为JSON使用JS文字语法的子集,所以直接将它回显到JS的上下文中不需要任何引用包装或解析。

输出如下:

var enterprises = <?php echo $json; ?>;

一旦JS执行,将导致变量enterprises成为您想要的数据结构。因此,您还需要删除此行:

enterprises = JSON.parse(enterprises);

FWIW,你原来的错误是由JS字符串文字中双重转义斜杠的需要引起的。因为您输出到字符串文字中,所以单个\"在JavaScript执行中被占用,并且不再用于JSON解析。要输出到JS字符串文字,首先需要转义转义。因此,您应该坚持我的上述更改(更不用说我推荐的更改需要更少的开销)。