2013-03-26 71 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