首页 > 解决方案 > 由于添加了双引号,json对象变成了字符串?

问题描述

我有来自 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": "{...}" }

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

这真让我抓狂。我是否错过了防止这种情况发生的步骤?

标签: phpjquerymysqljson

解决方案


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

您可以在服务器端执行以下操作:

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

在客户端,

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

推荐阅读