【问题标题】:Return already formatted JSON - Slim Framework返回已格式化的 JSON - Slim 框架
【发布时间】:2016-07-26 23:06:54
【问题描述】:

我正在使用 Slim 框架以 JSON 格式返回结果。

$app->get('/forecast_range/{latitude}/{longitude}/{timeStart}/{timeEnd}', function (Request $request, Response $response) {

    $latitude  = $request->getAttribute('latitude');
    $longitude = $request->getAttribute('longitude');
    $timeStart = $request->getAttribute('timeStart');
    $timeEnd   = $request->getAttribute('timeEnd');

    $timeStart = new DateTime($timeStart);  
    $timeEnd   = new DateTime($timeEnd);

    $coordinates[] = array('latitude' => $latitude, 'longitude' => $longitude);

    $forecast = new forecast_range_url($coordinates, 1, $timeStart, $timeEnd);
    $result = $forecast->runForecast(true);    

    return $response->withJson($result);

});

$result 变量已经是一个 JSON,一个多维的。我怎样才能将 $result 变量返回给客户端而无需再次对其进行编码?

我正在尝试使用此代码将 $result keysJSON 附加到响应中。我觉得我很接近但还没有。我收到语法错误。

 $lenght = count($result);        

    for ($i=0; $i<$lenght; $i++){
        $response->write($result[$i]);    
    }    

    $newResponse = $response->withHeader(
        'Content-type',
        'application/json; charset=utf-8'
    );

    return $newResponse;

【问题讨论】:

    标签: php http-headers slim slim-3


    【解决方案1】:
    return $response->write('{"json":"message"}')
              ->withHeader('Content-Type', 'application/json');
    

    直接写到流里,别忘了设置正确的content-type :)

    【讨论】:

    • 啊,我忘了提到 json 它是多维的。如果我把 return $response->write($result[0]) ->withHeader('Content-Type', 'application/json');它返回已经格式化的 json,但不是整个集合。 ://
    • 可能我需要循环 json 以作为参数发送到 write 方法..为此我需要解码然后再次编码...:/我对吗?
    • 是的。你需要这样做;(
    • $lenght = count($result); for ($i=0; $iwrite($result[$i])->withHeader('Content-Type', 'application/json'); } 返回 $response->getBody();
    • 我试过那个方法......它返回了数据,但他返回了一些格式错误的json......该死的! :) 这是一个巨大的数据集,需要再次解码和编码......:/
    【解决方案2】:

    我想我怎么能返回一个已经格式化的 JSON。 我需要将“,”和“[]”附加到response,否则数据将不会采用正确的 JSON 语法。

    这是我带来的:

    $result = $forecast->runForecast(true);        
    $lenght = count($result);              
    
        for ($i=0; $i<$lenght; $i++){         
            if ($i == 0){
                $response->write('['.$result[$i].',');                     
            }
            elseif($i == $lenght - 1)
            {
                $response->write($result[$i].']');
            }
            else
            {
                $response->write($result[$i].',');                        
            }
        }          
    
    $newResponse = $response->withHeader('Content-type', 'application/json; charset=utf-8');
    return $newResponse;
    

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 2012-12-18
      • 2021-01-02
      • 2018-03-22
      • 1970-01-01
      • 2012-07-09
      相关资源
      最近更新 更多