2

我正在尝试解码 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 片段存储在 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 

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

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

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

谢谢

4

2 回答 2

2

我看到的两个问题:

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

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

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

$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>";
    }
}
于 2013-08-30T21:39:55.390 回答
0

因为在解码基于 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
}
于 2013-08-31T20:16:28.277 回答