programing

JSON 문자열을 어레이로 변환하는 방법

yoursource 2022. 10. 2. 12:20
반응형

JSON 문자열을 어레이로 변환하는 방법

제가 하고 싶은 일은 다음과 같습니다.

  1. php의 텍스트 영역에서 입력으로 JSON을 받아들입니다.
  2. 이 입력을 사용하여 JSON으로 변환하고 php curl로 전달하여 요청을 보냅니다.

이 m은 get of api에서 php를 취득하여 이 json 문자열을 json에게 전달하고 싶지만 배열로 변환되지 않습니다.

echo $str='{
        action : "create",
        record: {
            type: "n$product",
            fields: {
                n$name: "Bread",
                n$price: 2.11
            },
            namespaces: { "my.demo": "n" }
        }
    }';
    $json = json_decode($str, true);

위의 코드가 어레이를 반환하지 않습니다.

게시물의 JSON을 다음 주소로 전달하면json_decode에러가 발생합니다.유효한 JSON 문자열에는 따옴표로 둘러싸인 키가 있습니다.

json_decode('{foo:"bar"}');         // this fails
json_decode('{"foo":"bar"}', true); // returns array("foo" => "bar")
json_decode('{"foo":"bar"}');       // returns an object, not an array.

이것을 시험해 보세요.

$data = json_decode($your_json_string, TRUE);

두 번째 파라미터는 디코딩된 json 문자열을 연관 배열로 만듭니다.

폼에서 JSON 문자열을 가져오는 경우$_REQUEST,$_GET, 또는$_POST이 기능을 사용해야 합니다.html_entity_decode()이 일을 하기 전까지는 몰랐습니다.var_dump복사한 내용과 복사한 내용을 비교합니다.echo요청 문자열이 훨씬 더 크다는 것을 알아챘습니다.

올바른 방법:

$jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);

오류가 있는 경우:

$jsonText = $_REQUEST['myJSON'];
$myArray = json_decode($jsonText, true);
echo json_last_error(); //Returns 4 - Syntax error;

사용하다json_decode($json_string, TRUE)JSON 개체를 배열로 변환하는 함수입니다.

예:

$json_string   = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

$my_array_data = json_decode($json_string, TRUE);

메모: 두 번째 파라미터는 디코딩된 JSON 문자열을 관련 배열로 변환합니다.

===========

출력:

var_dump($my_array_data);

array(5) {

    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

문자열은 다음 형식이어야 합니다.

$str = '{"action": "create","record": {"type": "n$product","fields": {"n$name": "Bread","n$price": 2.11},"namespaces": { "my.demo": "n" }}}';
$array = json_decode($str, true);

echo "<pre>";
print_r($array);

출력:

Array
 (
    [action] => create
    [record] => Array
        (
            [type] => n$product
            [fields] => Array
                (
                    [n$name] => Bread
                    [n$price] => 2.11
                )

            [namespaces] => Array
                (
                    [my.demo] => n
                )

        )

)

를 사용하여 URL에서 json 문자열을 가져오는 경우file_get_contents그 후 다음 절차를 따릅니다.

$url = "http://localhost/rest/users";  //The url from where you are getting the contents
$response = (file_get_contents($url)); //Converting in json string
 $n = strpos($response, "[");
$response = substr_replace($response,"",0,$n+1);
$response = substr_replace($response, "" , -1,1);
print_r(json_decode($response,true));

json이라고 하는 문자열에 문제가 있습니다.아래에 몇 가지 변경을 가했습니다.문자열 형식을 올바른 json으로 올바르게 지정하면 다음 코드가 작동합니다.

$str = '{
        "action" : "create",
        "record": {
            "type": "n$product",
            "fields": {
                "nname": "Bread",
                "nprice": 2.11
            },
            "namespaces": { "my.demo": "n" }
        }
    }';

    $response = json_decode($str, TRUE);
    echo '<br> action' . $response["action"] . '<br><br>';
<?php
$str='{
    "action" : "create",
    "record" : {
                "type": "$product",
                "fields": {
                           "name": "Bread",
                           "price": "2.11"
                           },
                "namespaces": { "my.demo": "n" }
                }
    }';
echo $str;
echo "<br>";
$jsonstr = json_decode($str, true);
print_r($jsonstr);

?>

이것은 효과가 있을 것이라고 생각합니다.키도 숫자가 아니면 큰따옴표로 묶어야 합니다.

이 솔루션: json 문자열$columns_validation = string(1736) "[{"colId":"N_ni","hide":true,"aggFunc":null,"width":136,"pivotIndex":null,"pinned":null,"rowGroupIndex":null},{"colId":"J_2_fait","hide":true,"aggFunc":null,"width":67,"pivotIndex":null,"pinned":null,"rowGroupIndex":null}]"

그래서 저는 json_module을 이렇게 두 번 사용합니다.

$js_column_validation = json_decode($columns_validation);
$js_column_validation = json_decode($js_column_validation); 

var_dump($js_column_validation);

결과는 다음과 같습니다.

 array(15) { [0]=> object(stdClass)#23 (7) { ["colId"]=> string(4) "N_ni" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(136) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL } [1]=> object(stdClass)#2130 (7) { ["colId"]=> string(8) "J_2_fait" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(67) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL }

문자열이 다음과 같은 JSON 형식인지 확인합니다.

{"result":"success","testid":"1"} (with " ") .

그렇지 않은 경우 추가 가능"responsetype => json"를 참조해 주세요.

그 후 사용json_decode($response,true)배열로 변환합니다.

json 객체를 Array & String으로 변환할 수 있습니다.

$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';

$b=json_decode($data);

$i=0;
while($b->{'resultList'}[$i])
{
    print_r($b->{'resultList'}[$i]->{'displayName'});
    echo "<br />";
    $i++;
}

개체로 변환하려면 다음을 수행합니다.

$data = json_decode($yourJson);

배열로 변환하는 경우:

$data = json_decode($yourJson,TRUE);

JSON 파일 또는 구조를 PHP 스타일 배열로 변환해야 할 경우 모든 중첩 수준을 사용하여 이 기능을 사용할 수 있습니다.먼저 json_decode($yourJ)를 입력해야 합니다.SONdata)를 사용하여 이 함수에 전달합니다.브라우저 창(또는 콘솔)에 올바른 PHP 스타일 배열이 출력됩니다.

https://github.com/mobsted/jsontophparray

이 변환기를 사용합니다. 전혀 실패하지 않습니다. Services_Json

// create a new instance of Services_JSON
$json = new Services_JSON();

// convert a complexe value to JSON notation, and send it to the browser
$value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
$output = $json->encode($value);
print($output);
// prints: ["foo","bar",[1,2,"baz"],[3,[4]]]

// accept incoming POST data, assumed to be in JSON notation
$input = file_get_contents('php://input', 1000000);
$value = $json->decode($input);

// if you want to convert json to php arrays:
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);

다음과 같이 문자열을 JSON으로 변경할 수 있습니다.또, 필요에 따라서, 스트링을 잘라내거나 떼어내거나 할 수도 있습니다.

$str = '[{"id":1, "value":"Comfort Stretch"}]';

//here is JSON object
$filters = json_decode($str);

foreach($filters as $obj){
   $filter_id[] = $obj->id;
}

//here is your array from that JSON
$filter_id;
 <?php

 $str='{
    "action" : "create",
    "record": {
        "type": "n$product",
        "fields": {
            "n$name": "Bread",
            "n$price": 2.11
        },
        "namespaces": { "my.demo": "n" }
    }
}';

 $json = json_decode($str,true);
 echo '<pre>';
 print_r($json);
 

키가 숫자가 아닐 경우 큰따옴표로 묶어야 합니다.

출력:-

  Array
 (
   [action] => create
   [record] => Array
     (
        [type] => n$product
        [fields] => Array
            (
                [n$name] => Bread
                [n$price] => 2.11
            )

         [namespaces] => Array
             (
                 [my.demo] => n
             )
       )
     ) 

Json 문자열을 어레이로 변환합니다.

언급URL : https://stackoverflow.com/questions/7511821/how-to-convert-json-string-to-array

반응형