簡體   English   中英

json_decode()-我在做什么錯?

[英]json_decode() - What am I doing wrong?

因此,我決定在Codeigniter中創建自己的助手來獲取JSON文件並將PokeAPI調用另存為JSON。

我創建的save 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\"}],...

我通過@ccKep解決了該問題。

我從saveJSON函數中刪除了JSON編碼,如下所示:

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;
    }
}

這解決了我收到的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM