javascript - 解析 JSON 文件以生成并返回另一个包含所需数据的 JSON

标签 javascript php json http

我需要解析给定的 JSON 文件,以查找通过 HTTP GET 传递的开始时间和结束时间之间发生的事件。在此范围内发生的事件应作为新的 JSON 编码响应返回。到目前为止,我已经提出了两种可能的解决方案。似乎都没有给我预期的 JSON 编码文件。

编辑:除了脚本未生成正确的 JSON 文件之外,我在 Chrome 上的开发人员控制台中收到以下错误: Uncaught TypeError: Cannot read property 'length' of null

解决方案1:

  $param1 = $_GET['startTime'];
  $param2 = $_GET['endTime'];
  $data = file_get_contents('./events.json');
  $json = json_decode($data, true);

  foreach ($json as $key => $value){
        if ($value > $param1 && $value < $param2) {
              echo "$key => $value"; }
        else { return; }
  }

解决方案2(传入相同的参数,每个循环不同):

  foreach ($json as $key => $value){
        if ($value >= $param1 && $value <= $param2) { 
              $tempFile = "tempEvents.json";
              $jsonArray = json_decode(file_get_contents($tempFile), true);
              array_push($jsonArray, array( 'title' => ????, 'start' => $param1, 'end' => $param2 ));
              file_put_contents($file, json_encode($jsonArray));
        }
        else { return; }
        echo json_encode('tempEvents.json');
  }

要解析的示例 JSON 文件:

  [
   {
    "Name":"Event 1",
    "Start Time":258147369,
    "End Time":369147258
   },
   {
    "Name":"Event 2",
    "Start Time":789456123,
    "End Time":159487263
   },
  ]

最佳答案

您应该在数组上使用 json_encode 以获得格式正确的 JSON 输出。我无法代表您的 if 语句的有效性,因为您没有提供任何示例数据,但这就是您应该如何进行转换:

$param1 = $_GET['startTime'];
$param2 = $_GET['endTime'];
$data = file_get_contents('./events.json');
$json = json_decode($data, true);
$output = array();

foreach ($json as $key => $value){
    if ($value > $param1 && $value < $param2)
        $output[$key] = $value;
}

$json_out = json_encode($output);
echo $json_out; // this outputs to the browser
// to output to file, use $json_out as your string to write to file

关于javascript - 解析 JSON 文件以生成并返回另一个包含所需数据的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23600856/

相关文章:

javascript - React.js如何避免某些组件的服务器渲染?

javascript - Sonarqube Javascript Coverage 不显示源文件

javascript - 从 JSON 响应中删除 '@' 作为 String() 后,在 WSO2 序列中使用 setPeyloadJSON() 时收到错误

javascript - 为什么Jquery ajax要给String添加斜杠?

javascript - 使 html/javascript 链接到 pdf 只能下载

javascript - DataTables+Datepicker 按日期范围过滤表格

php - 从 Controller 使用对象 Zend\View\Helper\Url

php - jqGrid setCell计算值

php - 如何使用 PHP 正确检索 JSON 字符串?

javascript - 如何循环遍历具有许多 JSON 数组节点的 JSON 对象 jQuery