【问题标题】:Decoding JSON in PHP在 PHP 中解码 JSON
【发布时间】:2013-09-03 16:47:39
【问题描述】:

我正在尝试解码 JSON 文件。

JSON 的摘录如下所示。为了更准确地描述这个 JSON,它是 3 X 组 JSON 代码。我正在尝试从第一行中提取与“main_train_uid”和“assoc_train_uid”相关的值,例如 G90491 和 G90525。

我一直在尝试复制 stackoverflow 各个部分中显示的代码示例,但失败了

我意识到这应该相对容易,但我就是不明白。我得到的输出是 Json 解码失败并出现错误:0。这表明没有错,但我没有得到值。我一直对数组和对象感到困惑。我的代码显示在 JSON 提取之后。

{"JsonAssociationV1":{"transaction_type":"Delete","main_train_uid":"G90491","assoc_train_uid":"G90525","assoc_start_date":"2013-09-07T00:00:00Z","location":"EDINBUR","base_location_suffix":null,"diagram_type":"T","CIF_stp_indicator":"O"}}
{"JsonAssociationV1":{"transaction_type":"Delete","main_train_uid":"P20328","assoc_train_uid":"P21318","assoc_start_date":"2013-08-23T00:00:00Z","location":"MARYLBN","base_location_suffix":null,"diagram_type":"T","CIF_stp_indicator":"C"}}
{"JsonAssociationV1":{"transaction_type":"Delete","main_train_uid":"L13077","assoc_train_uid":"L13045","assoc_start_date":"2013-08-23T00:00:00Z","location":"STPANCI","base_location_suffix":null,"diagram_type":"T","CIF_stp_indicator":"C"}}

JSON sn-p 存储在 json.txt 中

<?php

$file = "json.txt";
$trains = file_get_contents($file);

foreach (explode("\n", $trains) as $line) {

  $train = json_decode($line,true);

  if (is_array($train)) {

    foreach($train as $item=>$value) {

      foreach($value as $entry) {
        echo $entry->main_train_uid;
        echo $entry->assoc_train_uid;

      }
    }   
  } 
}               


if (is_null($json_train)) {
  die("Json decoding failed with error: ". json_last_error());
}

?>

感谢期待 约翰

编辑

感谢巴马尔

我的新代码如下

<?php
$file = "json.txt";


$trains = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($trains as $train) {
$json=json_decode($train,true);

foreach($json as $item=>$value) {
print_r($item);
foreach($value as $entry) {
echo '<br>';
print_r($entry);


}
}   
}   



if (is_null($json)) {
die("Json decoding failed with error: ". json_last_error());
}

?>

我现在得到以下输出(即值),没有错误,这很棒

JsonAssociationV1
Delete
G90491
G90525
2013-09-07T00:00:00Z
EDINBUR

T
OJsonAssociationV1
Delete
P20328
P21318
2013-08-23T00:00:00Z
MARYLBN

T
CJsonAssociationV1
Delete
L13077
L13045
2013-08-23T00:00:00Z
STPANCI

T
C 

但是,我仍然无法挑选出某些单独的值来自行回显(我需要这样做以便稍后将它们放入数据库中)。因此,例如,我仍然无法仅显示 ma​​in_train_uid

的值

另外,由于其中一个值为 NULL,它似乎将某些值向下推入下一组 JSON。例如上面输出中显示的 T 和 C

任何进一步的帮助表示赞赏

谢谢

【问题讨论】:

  • 如有疑问,请使用print_r,例如:$train = json_decode($line,true); echo '&lt;br&gt;' . print_r($train, true) . '&lt;br&gt;';
  • 没有变量$json_train,变量名是$train
  • 空值并没有压低任何东西,它们只是为这些值打印空行。这就是 echoprint_r 打印 null 和 false 值的方式,它们被打印为空字符串。使用var_dump,这样您就可以随时看到这些值。
  • 感谢您对这个 Barmar 的帮助。在您的帮助下,我现在可以了解个人价值观。再次感谢

标签: php json decoding


【解决方案1】:

我看到的两个问题:

首先,如果文件以换行符结尾,explode("\n", $trains) 将返回一个以空字符串结尾的数组。当您在该元素上调用 json_decode() 时,它将返回 NULLjson_last_error() == 0。试试:

foreach (array_filter(explode("\n", $trains) as $train)) {
    ...
}

或者,您可以使用file(),而不是file_get_contents()

$trains = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($trains as $train) {
    ...
}

其次,if (is_null($json_train)) 正在测试一个从未设置过的变量。正确的变量是$train

要从 JSON 中获取特定字段,请使用 $value['main_train_uid']

foreach ($trains as $train) {
    $json=json_decode($train,true);
    foreach ($json as $key => $value) {
        echo $key . "<br>" . $value['main_train_uid'] . "<br>";
    }
}

【讨论】:

  • 感谢 Barmar 和 OnetoOne。非常有帮助。我已经进行了进一步的编辑。肯定要往前走。刚刚在上面有一个进一步的查询。再次感谢
【解决方案2】:

因为您在解码基于 json 的消息时遇到错误,所以我发布了一种在发生异常时抛出异常的方法,以便您可以更好地处理错误。

您还可以扩展该类,以便它也可以处理编码

class Json {

   public static function decode($jsonString, $returnArray = true) {  
       if ((string)$jsonString !== $jsonString) {  // faster !is_string check
          throw new Exception('input should be a string');
       }

       $decodedString = json_decode($jsonString, $returnArray)

       if ((unset)$decodedString === $decodedString) { // faster is_null check, why NULL check because json_decode return NULL with failure. 
           $errorArray = error_get_last(); // fetch last error this should be the error of the json decode or it could be a date timezone error if you didn't set it correctly   

           throw new Exception($errorArray['message']); 
       }
       return $decodedString;
   }
}



try {
   Json::decode("ERROR");
} catch (Exception $e) {  }

例如,只需替换这一行

$json=json_decode($train,true);

有了这个

try {
   Json::decode($train,true);
} catch (Exception $e) {
  // handle json decode exception here note if you don't try catch the code will terminate
  // here you can handle what you want want to do
}

【讨论】:

  • 这很有用,雷蒙德。如何在脚本中调用它?
猜你喜欢
  • 2019-04-02
  • 2016-07-22
  • 1970-01-01
  • 2017-03-26
  • 2013-11-05
  • 2011-09-10
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
相关资源
最近更新 更多