2013-03-26 69 views
2

我从我的对象中提取数据没有问题。我的问题是编辑字符串中的数据并重新编码它。每次我尝试编辑对象时,它都会删除对象中的所有数据,并且只保存我编辑的内容。如何编辑使用json_decode()创建的PHP对象?

我会假设这工作,但它没有。有什么建议么? (下面显示的对象模式,我曾尝试它作为一个关联数组也得到相同的结果)

$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"}} 
+1

请出示的'$ jsonString'内容了。 – BenM 2013-03-26 15:45:18

+0

尝试打印'$ jsonString'和'$ newJsonString' :) – 2013-03-26 16:10:09

+1

那么,“stuff”实际上是否存在?如果没有PHP会提出一个警告,试图从一个空值创建一个默认对象 – Crisp 2013-03-26 16:10:10

回答

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

+0

我再次检查,仍然无法正常工作。我在上面和之后添加了我的字符串。 – pandasar 2013-03-26 17:10:59

+0

@ user2212224 - 我告诉过你,你正在读错的东西。看我的编辑。 – 2013-03-26 17:13:36

+0

好的,我怎么读它? – pandasar 2013-03-26 17:24:24

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作为sociative阵列

+0

我做了并得到了相同的结果 – pandasar 2013-03-26 15:58:11

+2

您*可以编辑PHP对象。没有必要切换到阵列。 – 2013-03-26 16:05:36