2

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

我会假设这行得通,但事实并非如此。有什么建议么? (下面以对象模式显示,我也尝试将它作为关联数组并得到相同的结果)

    $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"}}
4

2 回答 2

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 作为关联数组

于 2013-03-26T15:47:56.650 回答
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:如果事实上,您的数据不是有效的 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

于 2013-03-26T16:05:04.593 回答