首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用PHP的json_encode创建的JSON在解析错误中的结果

问用PHP的json_encode创建的JSON在解析错误中的结果
EN

Stack Overflow用户
提问于 2015-07-28 14:09:48
回答 2查看 2.4K关注 0票数 0

以以下PHP数组为例:

代码语言:javascript
复制
$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时,我得到以下字符串:

代码语言:javascript
复制
[{"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}]

注意,双引号使用反斜杠转义原始字符串中的。它看起来很好,甚至是验证。

当我试图在Chrome或Safari (使用JSON.parse())中解析JSON时,控制台中会出现以下错误:

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错误中,我收集到字符串中的第一个转义双引号似乎破坏了代码。

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

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

相关守则:

型号:

代码语言:javascript
复制
// 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;
}

主计长:

代码语言:javascript
复制
    // 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);

查看:

代码语言:javascript
复制
<script type="text/javascript">
    var enterprises = '<?php echo $json; ?>';
</script>

JavaScript:

代码语言:javascript
复制
if ($('#enterprises') && $('#enterprise-template').length && 'undefined' !== typeof enterprises) {
    enterprises = JSON.parse(enterprises);
    enterprisesCount = enterprises.length;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-28 14:35:20

你没有做任何“错误”的事情。其实你自己已经找到解决办法了!JavaScript生成的字符串可能是由echo-ing将其传输到一行JavasScript代码中,使用如下

代码语言:javascript
复制
var jsvar='<?= json_encode($arr) ?>';

结果会或多或少地像你在你的帖子中所显示的那样:

代码语言:javascript
复制
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-字符串如下所示:

代码语言:javascript
复制
'{"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()掩蔽所有的addslashes()。

代码语言:javascript
复制
var jsvar='<?= addslashes(json_encode($arr)) ?>';
var o=JSON.parse(jsvar);

或者,正如@JAAulde非常正确地发布的那样:您可以直接跳过变量的“`string”状态:

代码语言:javascript
复制
var o=<?= json_encode($arr)) ?>;
票数 6
EN

Stack Overflow用户

发布于 2015-07-28 14:37:40

由于JSON使用JS文字语法的子集,因此直接将其回显到JS的上下文中不需要任何引号包装或解析。

像这样输出:

代码语言:javascript
复制
var enterprises = <?php echo $json; ?>;

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

代码语言:javascript
复制
enterprises = JSON.parse(enterprises);

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31678815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档