2013-08-09 2 views
1

다음 코드를 사용하여 일부 JSON을 구문 분석하고 예기치 않은 JSON 결과가 계속 발생합니다.예상 JSON 페이로드가 올바른 JSON 페이로드를 반환하지 않음

그것은 here 출신이지만, 내가 선 57 $status에 있기 때문에 작업이 코드 아니었다는 $status가 배열이 아닌 있다는 사실에 관한 오류 던지는 그래서 배열을 가져올 수 없습니다 :

I을 검사를 추가하여 고정하는 것이 :

56 if (is_array($status)) {} 

이제 코드는 잘 실행하지만 JSON이 반환 된 다음과 같다 :

{"0":null,"1":" 0"} 

내 조약돌 시계에 an application을 실행하면 올바른 데이터를 표시하기위한 것이므로 0 안에 아무 것도 없기 때문에 분명히 실패하기 때문에 이것이 올바르지 않습니다.

다음 코드는 null 대신에 $order을 삽입해야한다고 말할 수 있습니다. 그러나 그 대신 어떤 이유로 든 항상 null을 반환합니다.

35 // Grab the tube status and the incoming payload. 
36 $tube_data = json_decode(file_get_contents($API_URL), true); 
37 $payload = get_payload(); 
38 
39 $order = $payload['0']; 
40 
41 // Start building the response. 
42 $response = array(
43 '0' => $order, 
44 '1' => '' 
45 ); 

어떤 도움을 주시면 대단히 감사하겠습니다. 여기

은 (유틸 포함) 전체 코드입니다 :

main.php

1 <?php 
2 
3 // Include my shared functions. 
4 include_once($_SERVER['DOCUMENT_ROOT'] . '/utils.php'); 
5 
6 // The URL of the Tube Status API. 
7 $API_URL = 'http://api.tubeupdates.com/?method=get.status&format=json'; 
8 
9 // Mapping between shortcode and line name. 
10 $line_codes = array(
11 'BL' => 'bakerloo', 
12 'CE' => 'central', 
13 'CI' => 'circle', 
14 'DI' => 'district', 
15 'DL' => 'docklands', 
16 'HC' => 'hammersmithcity', 
17 'JL' => 'jubilee', 
18 'ME' => 'metropolitan', 
19 'NO' => 'northern', 
20 'OV' => 'overground', 
21 'PI' => 'piccadilly', 
22 'VI' => 'victoria', 
23 'WC' => 'waterloocity' 
24 ); 
25 
26 // Mapping between errors and numbers 
27 $statuses = array(
28 'good service' => 1, 
29 'part closure' => 2, 
30 'minor delays' => 4, 
31 'severe delays' => 8, 
32 'part suspended' => 16 
33 ); 
34 
35 // Grab the tube status and the incoming payload. 
36 $tube_data = json_decode(file_get_contents($API_URL), true); 
37 $payload = get_payload(); 
38 
39 $order = $payload['0']; 
40 
41 // Start building the response. 
42 $response = array(
43 '0' => $order, 
44 '1' => '' 
45 ); 
46 
47 // Split the ordering string into the 2 character line short codes. 
48 $lines = str_split($order, 2); 
49 foreach ($lines as $pos => $line) { 
50 
51 // Get the status for the line given its short code. 
52 $status = get_status_by_id($line_codes[$line]); 
53 
54 // Do bitwise ORs on the status number to build it up 
55 $status_number = 0; 
56 if (is_array($status)) { 
57  foreach ($status as $st) { 
58  $status_number = $status_number |= $statuses[$st]; 
59  } 
60 } 
61 
62 // Append the status code to the response string. 
63 $response['1'] .= str_pad($status_number, 2, ' ', STR_PAD_LEFT); 
64 } 
65 
66 // Send the response. 
67 send_response($response); 
68 
69 // Takes a line code (not shortcode) and returns an array of its current status. 
70 function get_status_by_id($id) { 
71 global $tube_data; 
72 
73 foreach ($tube_data['response']['lines'] as $index => $line) { 
74  if ($line['id'] == $id) { 
75  return explode(', ', $line['status']); 
76  } 
77 } 
78 return NULL; 
79 } 
80 
81 ?> 

utils.php

<?php 

function get_payload() { 
    return json_decode(file_get_contents('php://input'), true); 
} 

function send_response($data) { 
    $response = json_encode($data, JSON_FORCE_OBJECT); 
    header('Content-Type: application/json'); 
    header('Content-Length: ' . strlen($response)); 
    echo $response; 
    exit; 
} 

?> 
+0

[예상 JSON 페이로드가 제대로 반환하지]의 중복 가능성 (http://stackoverflow.com/questions/18139137/expected-json-payload-not-returning-properly) – andrewsi

+0

@gotnull 아래의 내 대답은 귀하의 문제를 해결합니까? – Ray

답변

1

가 그대로 있다면, 소비자를 보호하기 위해 json 문자열 {"0":null,"1":" 0"}에 'null'이라는 단어를 반환하면 d 패턴을 ''로 바꿉니다.

$payload = file_get_contents('php://input'); 
$payload = str_replace(' null ', '""', $payload); 
return json_decode($payload, true); 

는 send_response를 해결하려면() 그래서 결코 당신이 중 하나에 인코딩하기 전에 배열을 iterrate 수있는 결과 '널'이 포함되지 않습니다 : 빈 문자열로

  1. 변화에 null을.

내가 1 번을 좋아 널 가리키는 어떤 인덱스를 삭제합니다

function send_response($data) { 
    foreach($data as $key=>$value){ 
      $data[$key] = is_null($value) ? '' : $value; 
    } 
    $response = json_encode($data, JSON_FORCE_OBJECT); 
    header('Content-Type: application/json'); 
    header('Content-Length: ' . strlen($response)); 
    echo $response; 
    exit; 
} 
관련 문제