안녕하세요

프로그램 과정에서 막혔던 문제들에 대한 해결책 정리


페이지 목록

레이블이 JSON인 게시물을 표시합니다. 모든 게시물 표시
레이블이 JSON인 게시물을 표시합니다. 모든 게시물 표시

2018년 2월 13일 화요일

PHP to JSON(PHP class를 JSON으로 변경하는 방법)

PHP to JSON- How to serialize PHP class to JSON format?

If you are using PHP to implement REST API, you will come across this question. The answer to this, in general, is really simple.
PHP comes with two functions json_encode and json_decode, for encoding a PHP object into JSON and JSON string into PHP object respectively.
Check out the manual at Php.Net for the full details of this function.
The call is simple $j = json_encode($v);
$j contains the JSON for $v which can be an array, object or scalar variable.
However, here are a few limitations to json_encode.
  1. If you have strings stored in the object your encoding, they have to be UTF-8 strings or you need to convert them to UTF-8 using utf8_encode before calling json_encode
  2. If you have member variables that are marked as private, json_encode can’t see them.
  3. Associative arrays will be represented as objects. Sequential arrays will be represented as arrays in JSON. You can force them to be represented as objects by either casting the variable to object or pass in the option JSON_FORCEOBJECT
Being able to expose private and protected variables is very important. This can be done in various ways. You can use an Iterator like an ArrayIterator and call json_encode on that. The solution I am going to outline involves writing your own custom encode function that uses json_encode.
As an example you take the following classes in PHP. JsonTest contains JSon_Test1 which in turn contains JSonTest_2.
class Marshall
{
public function propvalues()
{
return get_object_vars($this);
}
}
class JSonTest_2 extends Marshall
{
public $arr2;
public function __construct()
{
$this->arr2 = array(1 => “stest”, 4 =>”stest2″, 3=>5.1);
}
}
class JSonTest_1 extends Marshall
{
public $arr1;
public $j2;
private $jp2;
public function __construct()
{
$this->arr1 = array(“test”, “test2”);
$this->j2 = new JSonTest_2();
$this->jp2 = “jp2”;
}
public function propvalues()
{
return array(“arr1” =>$this->arr1, “j2″=>$this->j2->propvalues(), “jp2″=>$this->jp2);
}
}
class JsonTest extends Marshall
{
private $arrActuary = array();
public $jt1;
private $jt11;
private $arrTestM = array();
public function __construct()
{
$this->jt1 = new JSonTest_1();
$this->jt11 = new JSonTest_1();
$this->arrTestM = array(1 =>”value”, “test” =>100.21);
}
public function propvalues()
{
return array(“jt1″=>$this->jt1->propvalues(), “jt11″=>$this->jt11->propvalues(), “arrTestM”=>$this->arrTestM);
}
}
class JSon
{
static public function encode($o)
{
if(is_a($o, “Marshall”))
return json_encode($o->propvalues());
return json_encode($o);
}
}
The following code will call normal json_encode passing in $j and then call the special encode on $j.
$j = new JsonTest();
echo “normal encode”;
echo json_encode($j);
echo “special encode”;
echo JSon::encode($j);
This will echo the following two lines: (You can pretty print these to make them more readable etc.)
normal encode
{“jt1”:{“arr1”:[“test”,”test2″],”j2″:{“arr2”:{“1″:”stest”,”4″:”stest2″,”3″:5.1}}}}
special encode
{“jt1”:{“arr1”:[“test”,”test2″],”j2″:{“arr2”:{“1″:”stest”,”4″:”stest2″,”3″:5.1}},”jp2″:”jp2″},”jt11″:{“arr1”:[“test”,”test2″],”j2″:{“arr2”:{“1″:”stest”,”4″:”stest2″,”3″:5.1}},”jp2″:”jp2″},”arrTestM”:{“1″:”value”,”test”:100.21}}
I define a class called Marshall which when inherited automatically exposes all the public variables as an array. If you override the function propvalues in the inherited class as is done in the class JSonTest_1, you will be able to iterate over the private and protected variables too.
I also defined a helper class JSon with static function encode which calls json_encode on the object if it does not inherit from Marshall otherwise it will call propvalues function and json_encode the return value.
Here we make use of two properties of json_encode to achieve this. First one is the fact that json_encode recursively encodes the objects. Second one is that associative arrays are encoded as objects. The second property is the one that’s used in propvalues where we are constructing the associative array with the private, protected and public variables.
Note that propvalues itself can check if the contained class in this case JSonTest_2 is a Marshall class and call propvalues on it.
The code above has an advantage over normal json_encode function in that you can transform the class to be different from what it is in PHP when you serialize in JSON.. can be selective about which member variables in the class you want to add to JSON. You can also decide what to name them.
(Note – json_encode is available in 5.2 version or later and get_object_vars in PHP version 4.0 or later)

출처: https://mofintodev.wordpress.com/2013/07/09/php-to-json-how-to-serialize-php-class-to-json-format/

2015년 9월 1일 화요일

Json 특수문자 처리

하루 종일 고생했던 특수문자 드디어 처리했다 아래 블로그 주인장님 사랑합니다
qqqqqq.tistory.com/entry/JSON-표기법-응답-생성시-주의점

2013년 2월 13일 수요일

Json Example (Json 포멧)

JSON (JavaScript Object Notation)

JSON is an extremely light text-based open standard designed for human-readable data. It originates from the JavaScript language and is used representing simple data types, arrays and associative arrays (called objects).

JSON Example

ArrayArray elements are generally of a basic type (number, string, boolean, or null), however can also be a nested array or object (see Data Structures). Elements are comma-delimited and contained within brackets.
myArray = [ "John Doe", 29, true, null ]
myArray = [ [], {} ]
myArray[2] returns true

Array with objectsThis array contains comma-delimited objects which each contain multiple comma-delimited key:value pairs. Objects within an array can be accessed using the array name and index.
myArray = [
 { "name": "John Doe", "age": 29 }, 
 { "name": "Anna Smith", "age": 24 }, 
 { "name": "Peter Jones", "age": 39 }
]
myArray[0].name returns John Doe

ObjectThis object contains multiple comma-delimited key:value pairs. Object properties can be accessed using the the object name followed by a period and property name -or- can be accessed like an array using the property name in quotes (in place of an index).
myObject = {
 "first": "John",
 "last": "Doe",
 "age": 39,
 "sex": "M",
 "salary": 70000,
 "registered": true
}
myObject.salary returns 70000
myObject["salary"] returns 70000

Object with nested arrayThis object contains multiple comma-delimited key:value pairs and a nested array. The nested array can be accessed with the object name, property or 'key' containing the array and an array index.
myObject = {
 "first": "John",
 "last": "Doe",
 "age": 39,
 "sex": "M",
 "salary": 70000,
 "registered": true,
 "interests": [ "Reading", "Mountain Biking", "Hacking" ]
}
myObject.interests[0] returns Reading
myObject["interests"][0] returns Reading

Object with nested objectThis object contains multiple comma-delimited key:value pairs and a nested object. To access an object within an object, property names or 'keys' can be chained together -or- property names can be used like an array in place of indexes.
myObject = {
 "first": "John",
 "last": "Doe",
 "age": 39,
 "sex": "M",
 "salary": 70000,
 "registered": true,
 "favorites": {
  "color": "Blue",
  "sport": "Soccer",
  "food": "Spaghetti"
 } 
}
myObject.favorites.food returns Spaghetti
myObject["favorites"]["food"] returns Spaghetti

Object with nested arrays and objectsThis object is more complex and typical of what might come from an API. It contains key:value pairs, nested arrays and nested objects. Any of its elements can be accessed with a combination of the above techniques.
myObject = {
 "first": "John",
 "last": "Doe",
 "age": 39,
 "sex": "M",
 "salary": 70000,
 "registered": true,
 "interests": [ "Reading", "Mountain Biking", "Hacking" ],
 "favorites": {
  "color": "Blue",
  "sport": "Soccer",
  "food": "Spaghetti"
 }, 
 "skills": [
  {
   "category": "Javascript",
   "tests": [
    { "name": "One", "score": 90 },
    { "name": "Two", "score": 96 }
   ] 
  },
  {
   "category": "CouchDB",
   "tests": [
    { "name": "One", "score": 79 },
    { "name": "Two", "score": 84 }
   ] 
  },
  {
   "category": "Node.js",
   "tests": [
    { "name": "One", "score": 97 },
    { "name": "Two", "score": 93 }
   ] 
  }
 ]
}
myObject.skills[0].category returns Javascript
myObject["skills"][0]["category"] returns Javascript
myObject.skills[1].tests[0].score returns 79
myObject["skills"][1]["tests"][0]["score"] returns 79

Data Structures

Numbervar myNum = 123.456Double precision floating-point format in JavaScript; generally depends on implementation.
Stringvar myString = "abcdef"Series of characters (letters, numbers, or symbols); double-quoted UTF-8 with backslash escaping.
Booleanvar myBool = true(true or false)
Arrayvar myArray = [ "a", "b", "c", "d" ]Sequence of values, comma-separated and enclosed in square brackets; values don't need to be of the same type.
Objectvar myObject = { "id": 007 }Unordered collection of key:value pairs; comma-separated and enclosed in curly braces; the should be strings and be distinct.
Nullvar myNull = null(empty)

JSON Resources

JSONLintJSON validator


출처 :http://www.jsonexample.com/

Array

myArray = [ "John Doe", 29, true, null ]
myArray[2] returns true 

Array 형식은 myArray[0] ,myArray[1] 처럼 평소 사용하던 Array 사용 방법으로 사용할 수 있다.
0은 John Doe, 1 은 29를 반환한다.

Array with objects

myArray = [
 { "name": "John Doe", "age": 29 }, 
 { "name": "Anna Smith", "age": 24 }, 
 { "name": "Peter Jones", "age": 39 }
]
Array에 Object를 넣는 방법이다.

myArray[0].name returns John Doe
myArray[1].age 는 24를 return 하게 된다.

Object

object는 ":" 값을 기준으로 Key 값과 실제 값으로 매칭된다.
myObject = { "first": "John", "last": "Doe", "age": 39, "sex": "M", "salary": 70000, "registered": true }
myObject.salary returns 70000 myObject["salary"] returns 70000
위 두가지 방법으로 각각의 object를 추출 할 수 있다.
myobject.first 는 John을 반환하고,
myObject["first"] 로도 John을 반환할 수 있다.

Object with nested array

iterests 를 보면, interest 키 값에 Array가 대응될 수 있음을 알 수 있다.
myObject = {
 "first": "John",
 "last": "Doe",
 "age": 39,
 "sex": "M",
 "salary": 70000,
 "registered": true,
 "interests": [ "Reading", "Mountain Biking", "Hacking" ]
}
myObject.interests[0] returns Reading
myObject["interests"][0] returns Reading 
 
Object with nested arrays and objects

myObject = {
 "first": "John",
 "last": "Doe",
 "age": 39,
 "sex": "M",
 "salary": 70000,
 "registered": true,
 "interests": [ "Reading", "Mountain Biking", "Hacking" ],
 "favorites": {
  "color": "Blue",
  "sport": "Soccer",
  "food": "Spaghetti"
 }, 
 "skills": [
  {
   "category": "Javascript",
   "tests": [
    { "name": "One", "score": 90 },
    { "name": "Two", "score": 96 }
   ] 
  },
  {
   "category": "CouchDB",
   "tests": [
    { "name": "One", "score": 79 },
    { "name": "Two", "score": 84 }
   ] 
  },
  {
   "category": "Node.js",
   "tests": [
    { "name": "One", "score": 97 },
    { "name": "Two", "score": 93 }
   ] 
  }
 ]
}
myObject.skills[0].category returns Javascript
myObject["skills"][0]["category"] returns Javascript
myObject.skills[1].tests[0].score returns 79
myObject["skills"][1]["tests"][0]["score"] returns 79

위와 같이 복잡한 관계도 만들어 낼 수 있다.

기본 개념은 Array와 Object를 이용하여, Data를 Object Oriented 하게 만들어 내는 것인 듯 하다.

2013년 1월 31일 목요일

[JSON] JSON에 대해

JSON에 대해 아는 만큼 알려드리겠습니다.

JSON은 HTML과 비슷하게, 서버와 클라이언트 간에

정보를 주고 받는 규약으로 생각 됩니다.

JSON Form에 맞춰서 전송하면,

JSON을 이용하는 홈페이지에 해당 정보를

저장할 수 있게 되는 것입니다.

홈페이지에서 더 자세한 내용을 살펴 보세요.

http://www.json.org/json-ko.html