Programming

PHP로 JSON 파일을 파싱하려면 어떻게해야합니까?

procodes 2020. 2. 25. 22:54
반응형

PHP로 JSON 파일을 파싱하려면 어떻게해야합니까?


PHP를 사용하여 JSON 파일을 구문 분석하려고했습니다. 그러나 나는 지금 붙어 있습니다.

이것은 내 JSON 파일의 내용입니다.

{
    "John": {
        "status":"Wait"
    },
    "Jennifer": {
        "status":"Active"
    },
    "James": {
        "status":"Active",
        "age":56,
        "count":10,
        "progress":0.0029857,
        "bad":0
    }
}

그리고 이것은 내가 지금까지 시도한 것입니다.

<?php

$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);

echo $json_a['John'][status];
echo $json_a['Jennifer'][status];

그러나 이름 ( 'John', 'Jennifer')과 사용 가능한 모든 키와 값 ( 'age', 'count')을 미리 알지 못하기 때문에 foreach 루프를 만들어야한다고 생각합니다.

이에 대한 예를 들겠습니다.


다차원 배열을 반복하려면 RecursiveArrayIterator 를 사용할 수 있습니다.

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }
}

산출:

John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0

코드 패드에서 실행


JSON을 제대로 읽지 않으면 많은 사람들이 답변을 게시하고 있다고 믿을 수 없습니다.

$json_a혼자 반복 하는 경우 객체의 객체가 있습니다. true두 번째 매개 변수로 전달하더라도 2 차원 배열이 있습니다. 첫 번째 차원을 반복하는 경우 두 번째 차원 만 에코 할 수 없습니다. 따라서 이것은 잘못되었습니다.

foreach ($json_a as $k => $v) {
   echo $k, ' : ', $v;
}

각 사람의 상태를 에코하려면 다음을 시도하십시오.

<?php

$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
    // deal with error...
}

$json_a = json_decode($string, true);
if ($json_a === null) {
    // deal with error...
}

foreach ($json_a as $person_name => $person_a) {
    echo $person_a['status'];
}

?>

가장 우아한 솔루션 :

$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);

json 파일은 BOM없이 UTF-8로 인코딩되어야합니다. 파일에 BOM이 있으면 json_decode는 NULL을 리턴합니다.

또는

$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;

시험

<?php
$string = file_get_contents("/home/michael/test.json");
$json_a=json_decode($string,true);

foreach ($json_a as $key => $value){
  echo  $key . ':' . $value;
}
?>

당신의 시작 "태그"가 틀렸다는 것을 아무도 지적하지 않은 것은 저를 완전히 넘어서는 것입니다. {}을 사용하여 객체를 생성하고 []를 사용하여 배열을 생성 할 수 있습니다.

[ // <-- Note that I changed this
    {
        "name" : "john", // And moved the name here.
        "status":"Wait"
    },
    {
        "name" : "Jennifer",
        "status":"Active"
    },
    {
        "name" : "James",
        "status":"Active",
        "age":56,
        "count":10,
        "progress":0.0029857,
        "bad":0
    }
] // <-- And this.

이 변경으로 json은 객체 대신 배열로 구문 분석됩니다. 그리고 그 배열을 사용하면 루프 등 원하는대로 무엇이든 할 수 있습니다.


이 시도

$json_data = '{
"John": {
    "status":"Wait"
},
"Jennifer": {
    "status":"Active"
},
"James": {
    "status":"Active",
    "age":56,
    "count":10,
    "progress":0.0029857,
    "bad":0
  }
 }';

 $decode_data = json_decode($json_data);
foreach($decode_data as $key=>$value){

        print_r($value);
}

더 표준 답변 :

$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");

$array = json_decode($jsondata,true);

foreach($array as $k=>$val):
    echo '<b>Name: '.$k.'</b></br>';
    $keys = array_keys($val);
    foreach($keys as $key):
        echo '&nbsp;'.ucfirst($key).' = '.$val[$key].'</br>';
    endforeach;
endforeach;

그리고 출력은 다음과 같습니다

Name: John
 Status = Wait
Name: Jennifer
 Status = Active
Name: James
 Status = Active
 Age = 56
 Count = 10
 Progress = 0.0029857
 Bad = 0

foreach키-값 쌍으로 루프를 사용하여 JSON을 반복합니다. 더 많은 루핑을 수행해야하는지 확인하려면 형식 검사를 수행하십시오.

foreach($json_a as $key => $value) {
    echo $key;
    if (gettype($value) == "object") {
        foreach ($value as $key => $value) {
          # and so on
        }
    }
}

시험:

$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);

foreach ($json as $key => $value) {
    if (!is_array($value)) {
        echo $key . '=>' . $value . '<br />';
    } else {
        foreach ($value as $key => $val) {
            echo $key . '=>' . $val . '<br />';
        }
    }
}

<?php
$json = '{
    "response": {
        "data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
        "status": 0,
        "totalRows": 83,
        "startRow": 0,
        "endRow": 82
    }
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status']; 
echo $json['response']['totalRows']; 
echo $json['response']['startRow']; 
echo $json['response']['endRow']; 

?>

시도 해봐:

foreach ($json_a as $key => $value)
 {
   echo $key, ' : ';
   foreach($value as $v)
   {
       echo $v."  ";
   }
}

json 문자열을 해독하면 객체가 생깁니다. 배열이 아닙니다. 따라서 얻는 구조를 보는 가장 좋은 방법은 디코딩의 var_dump를 만드는 것입니다. 이 var_dump는 주로 복잡한 경우에 구조를 이해하는 데 도움이됩니다.

<?php
     $json = file_get_contents('/home/michael/test.json');
     $json_a = json_decode($json);
     var_dump($json_a); // just to see the structure. It will help you for future cases
     echo "\n";
     foreach($json_a as $row){
         echo $row->status;
         echo "\n";
     }
?>

$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);



foreach($json_a as $person => $value)
{
    foreach($value as $key => $personal)
    {
        echo $person. " with ".$key . " is ".$personal;
        echo "<br>";
    }

}

모든 json 값을 반향하는 가장 빠른 방법은 루프 인 루프를 사용하는 것입니다. 첫 번째 루프는 모든 객체를 가져오고 두 번째 루프는 값을 가져옵니다 ...

foreach($data as $object) {

        foreach($object as $value) {

            echo $value;

        }

    }

다음과 같이 제공해야합니다.

echo  $json_a['John']['status']; 

echo "<>"

echo  $json_a['Jennifer']['status'];

br inside <>

결과는 다음과 같습니다.

wait
active

JSON을 배열로 변환하기 위해 아래 코드를 사용하고 있습니다 PHP.JSON이 유효하면 json_decode()잘 작동하고 배열을 반환하지만 잘못된 JSON의 경우 NULL,

<?php
function jsonDecode1($json){
    $arr = json_decode($json, true);
    return $arr;
}

// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
?>

잘못된 JSON 형식 인 경우 배열 만 필요한 경우이 함수를 사용할 수 있습니다.

<?php
function jsonDecode2($json){
    $arr = (array) json_decode($json, true);
    return $arr;
}

// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
?>

형식이 잘못된 JSON의 경우 코드 실행을 중지하려는 경우이 함수를 사용할 수 있습니다.

<?php
function jsonDecode3($json){
    $arr = (array) json_decode($json, true);

    if(empty(json_last_error())){
        return $arr;
    }
    else{
        throw new ErrorException( json_last_error_msg() );
    }
}

// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
?>

참고 URL : https://stackoverflow.com/questions/4343596/how-can-i-parse-a-json-file-with-php



반응형