php - 由于添加了双引号,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": "{...}" }
结果值是一个字符串,因为那些双引号!
这真让我抓狂。我是否错过了防止这种情况发生的步骤?
解决方案
工作正常,因为它按照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
}
推荐阅读
- google-plus - G Suite Marketplace 上的“plus.me”范围应该替换什么?
- javascript - 如何创建用户特定的 MongoDB 集合?
- python-3.x - 如何将字典的键作为熊猫数据框中的列值?
- javascript - 猫鼬中的参考是什么意思?
- r - 将白色背景添加到 plot.xts() 图例 [R]
- azure - Azure Kubernetes Service 将 docker root 更改为 /mnt(/dev/sdb1 临时存储)
- javascript - 如何将库添加到 webpacker 以在 Stimulus JS 控制器中使用
- php - 在 HTML 页面中使用 PHP 创建指向另一个页面或目录的操作链接
- laravel - Laravel - 如何根据数据库值创建一个带有特定条目的下拉列表
- unity3d - Unity Animator.Play 如何同时过渡到另一个动画