반응형
JSON 오브젝트 작성 방법
PHP 배열에서 JSON 개체를 생성하려고 합니다.어레이는 다음과 같습니다.
$post_data = array('item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts);
JSON을 인코딩하는 코드는 다음과 같습니다.
$post_data = json_encode($post_data);
JSON 파일은 최종적으로 다음과 같이 표시됩니다.
{
"item": {
"is_public_for_contacts": false,
"string_extra": "100000583627394",
"string_value": "value",
"string_key": "key",
"is_public": true,
"item_type_id": 4,
"numeric_extra": 0
}
}
생성된 JSON 코드를 "항목"에 캡슐화하는 방법: {JSON CODE HERE }.
보통 다음과 같은 작업을 수행합니다.
$post_data = json_encode(array('item' => $post_data));
다만, 출력은 「」로 하고 싶은 것 같습니다.{}
" 를 전달함으로써 오브젝트로서 부호화를 강제하는 것을 확인해 주세요.JSON_FORCE_OBJECT
일정한.
$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);
"{}
" 대괄호는 객체를 지정합니다.[]
"는 JSON 사양에 따라 어레이에 사용됩니다.
여기에 게재되어 있는 다른 답변은 유효하지만, 다음과 같은 접근방식이 보다 자연스럽습니다.
$obj = (object) [
'aString' => 'some string',
'anArray' => [ 1, 2, 3 ]
];
echo json_encode($obj);
php 어레이에 다른 레이어가 필요합니다.
$post_data = array(
'item' => array(
'item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts
)
);
echo json_encode($post_data);
범용 개체를 인코딩할 수 있습니다.
$post_data = new stdClass();
$post_data->item = new stdClass();
$post_data->item->item_type_id = $item_type;
$post_data->item->string_key = $string_key;
$post_data->item->string_value = $string_value;
$post_data->item->string_extra = $string_extra;
$post_data->item->is_public = $public;
$post_data->item->is_public_for_contacts = $public_contacts;
echo json_encode($post_data);
$post_data = [
"item" => [
'item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts
]
];
$post_data = json_encode(post_data);
$post_data = json_decode(post_data);
return $post_data;
언급URL : https://stackoverflow.com/questions/3281354/how-to-create-a-json-object
반응형
'sourcecode' 카테고리의 다른 글
MySQL의 외부 키 기본 사항 (0) | 2023.01.10 |
---|---|
텍스트 파일을 수정하는 방법 (0) | 2023.01.10 |
Javascript(글로벌 변수 포함)의 변수 선언 구문의 차이는? (0) | 2022.12.26 |
perl - 2개의 데이터베이스에서 2개의 SQL 쿼리로 이루어진 2개의 열을 비교합니다. (0) | 2022.12.26 |
org.codehouse.com과 com.codexml.core의 비교 (0) | 2022.12.26 |