如何编辑使用json_decode()创建的PHP对象?

时间:2013-03-26 15:43:27

标签: php json

从我的对象中提取数据没有问题。我的问题是编辑字符串中的数据并重新编码。每次我尝试编辑对象时,它都会删除对象中的所有数据,只保存我编辑的内容。

我会认为这有效,但事实并非如此。有什么建议? (以下显示在对象模式下,我也尝试将其作为关联数组并获得相同的结果)

    $jsonString = '[{ "stuff" : [{"name" : "name", "description" : "description", "id" : "id",}], "morestuff" : []}]';
    $name = 'new name';
    $description = 'new description';
    $obj_json = json_decode($jsonString);
    $obj_json->stuff->name = $name;
    $obj_json->stuff->description = $description;
    $newJsonString = json_encode($obj_json);

以下是打印的内容:

{ "stuff" : {"name" : "new name", "description" : "new description"}}

2 个答案:

答案 0 :(得分:2)

你的代码似乎是正确的,但试试这个(也许有修改对象的东西..):

$obj_json = json_decode($jsonString, true); //as associative array
$obj_json['stuff']['name'] = $name;
$obj_json['stuff']['description'] = $description;
$newJsonString = json_encode($obj_json);

使用json作为关联数组

答案 1 :(得分:1)

做你问的问题没问题:

<?php

$jsonString = '{
    "stuff": {
        "name": "Original name",
        "description": "Original description",
        "foo": "Another field"
    }
}';
$name = "New name";
$description = "New description";

$obj_json = json_decode($jsonString);
$obj_json->stuff->name = $name;
$obj_json->stuff->description = $description;
$newJsonString = json_encode($obj_json);

echo $newJsonString . PHP_EOL;

...打印:

{"stuff":{"name":"New name","description":"New description","foo":"Another field"}}

你可能正在阅读或写错了属性。

修改

仔细观察,您的数据被包装在一个数组中,而stuff本身也是一个数组:

$jsonString = '[{ "stuff" : [{"name" : "name", "description" : "description", "id" : "id",}], "morestuff" : []}]';
               ^            ^                                                              ^                   ^
               |            \______________________________________________________________/                   |
               \_______________________________________________________________________________________________/

修改#2 :事实上,您的数据为not valid JSONjson_decode()返回null

$jsonString = '[{ "stuff" : [{"name" : "name", "description" : "description", "id" : "id",}], "morestuff" : []}]';
$obj_json = json_decode($jsonString);
var_dump($obj_json, json_last_error());
NULL
int(4)

错误#4是JSON_ERROR_SYNTAX:语法错误,格式错误的JSON