laravelÊý×éתjson
laravel ÊÇÒ»¸öºÜÊÇÊ¢ÐÐµÄ php ¿ò¼Ü£¬ÌṩÁ˸»ºñµÄ php ¿ª·¢¹¤¾ßºÍ¿â¡£ÔÚ laravel ÖУ¬ÎÒÃǾ³£ÐèÒª½« php Êý×éת»»Îª json ÃûÌã¬ÕâÔÚÊý¾Ý½»»¥µÈ³¡¾°ÖзǾ³£¼û¡£
ÔÚ Laravel ÖУ¬ÓжàÖÖ·½·¨¿ÉÒÔ½« PHP Êý×éת»»Îª JSON¡£±¾ÎĽ«ÏÈÈݼ¸ÖÖ³£¼ûµÄת»»·½·¨£¬²¢ÌṩÏìÓ¦µÄʾÀý´úÂë¡£
ÒªÁìÒ»£ºÊ¹Óà PHP ÄÚÖú¯Êý json_encode()
PHP ÄÚÖõĺ¯Êý json_encode() ¿ÉÒÔ½« PHP Êý×éת»»Îª JSON ÃûÌá£Ê¾Àý´úÂëÈçÏ£º
$data = ['name' => 'Jack', 'age' => 28]; $json = json_encode($data); echo $json;
µÇ¼ºó¸´ÖÆ
Êä³öЧ¹ûΪ£º
{"name":"Jack","age":28}
µÇ¼ºó¸´ÖÆ
˵Ã÷ json_encode() º¯Êý½« PHP Êý×éת»»ÎªÁË JSON ×Ö·û´®¡£
ÒªÁì¶þ£ºÊ¹Óà Laravel ÖÐµÄ Response
ÔÚ Laravel ÖУ¬¿ÉÒÔʹÓà Response ÀàÀ´·µ»Ø JSON ÃûÌõÄÊý¾Ý¡£Ê¾Àý´úÂëÈçÏ£º
$data = ['name' => 'Jack', 'age' => 28]; return response()->json($data);
µÇ¼ºó¸´ÖÆ
ÕâЩ´úÂë¿ÉÒÔÔÚ Laravel ¿ØÖÆÆ÷µÄº¯ÊýÖÐʹÓ᣷µ»ØµÄ JSON Êý¾Ý½«±»×Ô¶¯ÉèÖÃÏìӦͷºÍ״̬Âë¡£
ÒªÁìÈý£ºÊ¹Óà Laravel ÖÐµÄ JsonResponse
ÔÚ Laravel ÖУ¬»¹¿ÉÒÔʹÓà JsonResponse ÀàÀ´ÌìÉú JSON Êý¾Ý¡£Ê¾Àý´úÂëÈçÏ£º
$data = ['name' => 'Jack', 'age' => 28]; return new IlluminateHttpJsonResponse($data);
µÇ¼ºó¸´ÖÆ
ÕâЩ´úÂ뽫·µ»ØÒ»¸ö JSON ÏìÓ¦£¬ÆäÖÐ $data ÊÇ PHP Êý×é¡£
ÒªÁìËÄ£ºÊ¹Óà Laravel ÖÐµÄ Collection
ÔÚ Laravel ÖУ¬¿ÉÒÔʹÓà Collection À´²Ù×÷Ò»×éÊý¾Ý¡£Collection ¿ÉÒÔºÜÀû±ãµØ½« PHP Êý×éת»¯Îª JSON Êý¾Ý¡£ ʾÀý´úÂëÈçÏ£º
$data = collect(['name' => 'Jack', 'age' => 28]); $json = $data->toJson(); echo $json;
µÇ¼ºó¸´ÖÆ
ÕâЩ´úÂëͨ¹ý½« PHP Êý×éת»»Îª Collection ¹¤¾ß£¬È»ºóŲÓà toJson() ÒªÁ죬½« Collection ת»»Îª JSON ×Ö·û´®¡£×îÖÕÊä³öµÄЧ¹ûÓëÒªÁìÖðÒ»Ö¡£
×ܽá
±¾ÎÄÏÈÈÝÁË Laravel Öг£ÓõÄËÄÖÖ½« PHP Êý×éת»»Îª JSON µÄÒªÁ죺ʹÓà PHP ÄÚÖú¯Êý json_encode()£¬Ê¹Óà Laravel ÖÐµÄ Response£¬Ê¹Óà Laravel ÖÐµÄ JsonResponse ºÍʹÓà Laravel ÖÐµÄ Collection¡£ÔÚÏÖʵӦÓÃÖУ¬Æ¾Ö¤ÏêϸÇéÐΣ¬¿ÉÒÔÑ¡ÔñÊʺÏ×Ô¼ºµÄת»»·½·¨¡£
ÒÔÉϾÍÊÇlaravelÊý×éתjsonµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡