【问题标题】:json object becoming string because double quotes are added?由于添加了双引号,json对象变成了字符串?
【发布时间】:2019-08-09 06:33:25
【问题描述】:

我有来自 MySql 的数据,回答如下: How to SQL query parent-child for specific JSON format?。基本上我使用JSON_OBJECT() 查询它,它会产生结果:

results<-- The column name

{"projects": "project_name": "project 1", [2nd layer stuff]}  <-- the row

太棒了。 MySql 为我做了 json 的事情。我对 PHP 函数进行了 ajax 调用,以将其传送到 Web 服务器上。:

myPhpFunction () {
    //some usual PDO code
    echo json_encode($query_result);
}

在 JS 上,我做了一个 jQuery ajax 调用:

var ajaxRequest =
$.ajax({
        type: 'post',
        url: '../includes/ajax.php',
        data: 'action' : 'myPhpFunction',
        dataType: 'json'
      });

      ajaxRequest.done(function(data) { 
        //$.each(data[0].results.projects, function(key, val){ 
            //I want to access each stuff in the object here
        //}
        $('#ph-projects').append(JSON.stringify(data)); //testing it out
      }

此时我遇到的问题是,我的对象 data 输出如下:

{ "results": "{...}" }

结果值是一个字符串,因为这些双引号!

这快把我逼疯了。我是否错过了防止这种情况发生的步骤?

【问题讨论】:

  • 如果你的 MYSQL 已经返回了一个 json 字符串,为什么还要重新编码呢?
  • 如果我不在 php 中做 json_encode(),我的 JS 说它会得到一个数组
  • 你能用JSON.parse(data)代替stringify吗?
  • 您需要展示如何获取行并对其进行编码。这就是问题所在。
  • @Rollor 你能在return json_encode($query_result); 之前做一个die(gettype($query_result)); 并发布结果吗?如果它是一个数组,请执行die(gettype($query_result['results']));

标签: php jquery mysql json


【解决方案1】:

json_encode() 工作正常,因为它按照您的问题 ({ "results": "{...}" }) 的建议将结果作为 JSON 对象提供。并且 PDO 中的 JSON_OBJECT() 返回字符串很好,正如名称 JSON 所暗示的那样,它的 JavaScript Object Notation 采用人类可读的格式。

你可以在服务器端做:

json_encode(['results'=&gt; json_decode($query_result['results'])]);

在客户端,

function(data){ 
    data.results = JSON.parse(data.results);
    // Your json data here
}

【讨论】:

  • 谢谢!我只尝试了客户端版本:var jdata = JSON.parse(data[0].results);,然后在jdata上工作
猜你喜欢
  • 2019-04-15
  • 1970-01-01
  • 2018-10-17
  • 2021-12-16
  • 2016-04-16
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
  • 2020-12-07
相关资源
最近更新 更多