在php中编辑json字符串


editing json string in php

我正试图通过javascript、来使用php编辑数据查询

我的ajax请求看起来像

var totalSearchResult=10;
$.ajax({
    url:"php/queryManipulation.php",
    type: 'POST',
    data: { totalQuery : totalSearchResult,  query : '{"data":{"match_all":{}}}'},
    success: function(finalList)
    {
        alert(finalList);
    }
});

我的php代码看起来像

<?php
$from=$_POST["totalQuery"];
$qry=json_decode($_POST["query"]);
$qry->from=$from;   }?>

,我正在试着把它写进表格里

{"data": {"match_all": {}} , "from": 10}

我得到错误Object of class stdClass could not be converted to string

编辑:已将json_decode返回值从数组更改为对象

您需要在完成编辑后再次对json进行编码。所以你可以做的是:

<?php
    $from            = $_POST["totalQuery"];
    $qry             = json_decode($_POST["query"]);
    $qry->data->from = $from;
    //you will get the new json string 
    //as the finalList variable in your post callback
    echo json_encode($qry); 
?>

您应该使用json_decode($string,true),所以它将是一个数组。此处提供详细信息:http://php.net/manual/en/function.json-decode.php

您可以解码为数组(不确定对象)并重新编码:

$qry = json_decode($_POST['query'], TRUE);
$qry['from'] = 10;
$new_qry = json_encode($qry);