2017-10-07 202 views
0

所以我決定在Codeigniter中創建自己的幫手來獲取JSON文件並將PokeAPI調用保存爲JSON。json_decode() - 我做錯了什麼?

的保存方法JSON我創作的作品罰款:

if (! function_exists('saveJson')) { 
    function saveJson($file, $data) { 
     $fp = fopen($file, 'w'); 
     fwrite($fp, json_encode($data)); 
     fclose($fp); 
    } 
} 

然而,功能的getJSON工作非常隨機。它適用於獲取某些文件,但其他人會拋出此錯誤:消息:json_decode()期望參數1是字符串,給定的數組。(所有的JSON文件是相同的格式)

的getJSON功能:

if (! function_exists('getJson')) { 
    function getJson($file) { 
     $json = file_get_contents($file); 
     $data = json_decode($json, true); 
     $pkm = json_decode($data, true); 
     return $pkm; 
    } 
} 

其奇,我必須將JSON兩次解碼或可我不能在我的意見訪問陣列。

我的模型和控制器就這一問題進一步深入: 型號功能例如:

function getPokemonById($id) { 
     $filepath = './assets/jsonsaves/pokemoncalls/'. $id. '.json'; 
     if(file_exists($filepath)) { 
     $pokemonByIdData = getJson($filepath); 
     } else { 
     $url = $this->pokemonApiAddress.$id.'/'; 
     $response = Requests::get($url); 
     saveJson($filepath, $response); 
     $pokemonByIdData = json_decode($response->body, true); 
     } 
     return $pokemonByIdData; 
    } 

控制器功能例如:

public function viewPokemon($id) { 
     $singlePokemon['pokemon'] = $this->pokemon_model->getPokemonById($id); 
     $singlePokemon['species'] = $this->pokemon_model->getPokemonSpecies($id); 
     $data['thepokemon'] = $this->pokemon_model->getAllPokemon(); 
    $this->load->view('template/header', $data); 
     $this->load->view('pokemonpage', $singlePokemon); 
    $this->load->view('template/footer'); 
    } 

所以在我的JSON文件中的一些變化。在一個JSON文件不起作用它,開頭:

{"body":"{\"forms\":[{\"url\":\"https:\\\/\\\/pokeapi.co\\\/api\\\/v2\\\/pokemon-form\\\/142\\\/\",\"name\":\"aerodactyl\"}],... 

但是這一個工程:

"{\"forms\":[{\"url\":\"https:\\\/\\\/pokeapi.co\\\/api\\\/v2\\\/pokemon-form\\\/6\\\/\",\"name\":\"charizard\"}],... 
+0

你可以發佈你的JSON文件內容的例子嗎? – barni

+1

'$ data'已經解碼json,你爲什麼要重新解碼它? '$ data = json_decode($ json,true); $ pkm = json_decode($ data,true);' - 這隻會在第一個json_decode返回一個字符串時才起作用,而這對解碼無濟於事。 – ccKep

+0

作爲一般經驗法則:您在保存方法中執行的每個操作也可以在您的加載方法中進行,反之亦然。在保存方法中,您可以** ** **編碼,您可以** ** **在您的加載方法中進行解碼。 – ccKep

回答

1

我解決了該問題由於@ccKep。

我刪除了JSON編碼從我saveJSON功能,像這樣:

if (! function_exists('saveJson')) { 
    function saveJson($file, $data) { 
     $fp = fopen($file, 'w'); 
     fwrite($fp, $data); 
     fclose($fp); 
    } 
} 

然後從我的getJSON功能去除第二json_decode:

if (! function_exists('getJson')) { 
    function getJson($file) { 
     $json = file_get_contents($file); 
     $data = json_decode($json, true); 
     return $data; 
    } 
} 

這個固定我收到了錯誤。