我开始使用silex开发rest api。这是我的第一个api!
我做了什么:
更新 代码改进了Federic的提示。添加使用Symfony JsonResponse。暂时不工作。
<?php
require_once __DIR__.'/vendor/autoload.php';
use Symfony\Component\HttpFoundation\JsonResponse;
// init Silex app
$app = new Silex\Application();
$app['debug'] = true;
//configure database connection
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => array(
'driver' => 'pdo_mysql',
'host' => '127.0.0.1',
'dbname' => 'db',
'user' => 'root',
'password' => '',
'charset' => 'utf8',
),
));
$app->get('/apps', function () use ($app){
$sql = "select apps.id, apps.guid, apps.title, clients.client, countries.country, langs.lang, apps.active from apps
inner join countries on apps.id_country = countries.id
inner join clients on clients.id = apps.id_client
inner join langs on langs.id = apps.id_lang
order by apps.created_at desc";
$results = $app['db']->fetchAll($sql);
$response['status'] = array(
'code' => 200,
'message' => 'OK'
);
$response['data'] = $results;
//return $app->json($response);
$jsonResponse = new JsonResponse($response);
$jsonResponse->setEncodingOptions(JsonReponse::DEFAULT_ENCODING_OPTIONS | JSON_PRETTY_PRINT);
return $jsonResponse;
});
$app->run();
它返回什么?
{"status":{"code":200,"message":"OK"},"data":[{"id":"2","guid":"a8559e9b-d850-4964-b672-335a87fe9e8b","title":"Coverdine Plus Light","client":"Servier","country":"England","lang":"English","active":"1"},{"id":"1","guid":"4f242e9d-c041-4c79-bc82-b62604de403c","title":"Coverdine","client":"Servier","country":"England","lang":"English","active":"0"}]}
如何使用JSON_PRETTY_PRINT
来改善人类对json对象的读取?
答案 0 :(得分:3)
而不是使用$app->json($response);
,而是使用JsonResponse
。您可以使用JSON_PRETTY_PRINT
方法设置setEncodingOptions
标记。
<?php
use Symfony\Component\HttpFoundation\JsonResponse;
// ...
$jsonResponse = new JsonResponse($response);
$jsonResponse->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | JSON_PRETTY_PRINT);
return $jsonResponse;
答案 1 :(得分:2)
这对我有用:
import random
def dice():
print random.randint(1,6)
dice()
答案 2 :(得分:0)
我也有这个困难,经过大量研究后我发现了函数:do_dump,click here在github中看到它。
要使用它,请执行以下操作:
$var = json_decode('{"a":1,"b":2,"c":3,"d":4,"e":5}');
do_dump($var);