Estoy escribiendo una demostración personalizada de REST API; ahora puede devolver números y cadenas en mi demo, pero quiero que devuelva un objeto JSON como otras API REST.
En mi demo, llamo a la API de Magento 2 (es decir, obtengo información del cliente: http: //localhost/index.php/rest/V1/customers/1 ) con curl, y devuelve una cadena JSON:
"{\" id \ ": 1, \" group_id \ ": 1, \" default_billing \ ": \" 1 \ ", \" created_at \ ": \" 2016-12-13 14: 57: 30 \ " , \ "updated_at \": \ "2016-12-13 15:20:19 \", \ "created_in \": \ "Default Store View \", \ "email \": \ "[email protected] \ ", \" nombre \ ": \" azol \ ", \" apellido \ ": \" young \ ", \" store_id \ ": 1, \" website_id \ ": 1, \" direcciones \ ": [{ \ "id \": 1, \ "customer_id \": 1, \ "region \": {\ "region_code \": \ "AR \", \ "region \": \ "Arad \", \ "region_id \ ": 279}, \" region_id \ ": 279, \" country_id \ ": \" RO \ ", \" street \ ": [\" abc \ "], \" phone \ ": \" 111 \ ",\"código postal\":\"1111 \ ", \" city \ ": \" def \ ", \" firstname \ ": \" azol \ ", \" lastname \ ": \" young \ ", \" default_billing \ ": true}], \ "disable_auto_group_change \": 0} "
La respuesta es una cadena JSON, pero todas las claves tienen una barra diagonal. Sé que puedo eliminar la barra diagonal str_replace, pero es una forma estúpida. ¿Hay alguna otra forma de devolver un objeto JSON sin barras dentro de las claves?
************ ACTUALIZACIÓN 2016.12.27 ************
Pegué mi código de prueba aquí:
   $method = 'GET';
    $url = 'http://localhost/index.php/rest/V1/customers/1';
    $data = [
        'oauth_consumer_key' => $this::consumerKey,
        'oauth_nonce' => md5(uniqid(rand(), true)),
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_timestamp' => time(),
        'oauth_token' => $this::accessToken,
        'oauth_version' => '1.0',
    ];
    $data['oauth_signature'] = $this->sign($method, $url, $data, $this::consumerSecret, $this::accessTokenSecret);
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => [
            'Authorization: OAuth ' . http_build_query($data, '', ','),
            'Content-Type: application/json'
        ], 
    ]);
    $result = curl_exec($curl);
    curl_close($curl);
    // this code has slash still
    //return stripslashes("hi i\" azol"); 
    // has slashes still
    //return stripcslashes("{\"id\":1,\"group_id\":1,\"default_billing\":\"1\",\"created_at\":\"2016-12-13 14:57:30\",\"updated_at\":\"2016-12-13 15:20:19\",\"created_in\":\"Default Store View\",\"email\":\"[email protected]\",\"firstname\":\"azol\",\"lastname\":\"young\",\"store_id\":1,\"website_id\":1,\"addresses\":[{\"id\":1,\"customer_id\":1,\"region\":{\"region_code\":\"AR\",\"region\":\"Arad\",\"region_id\":279},\"region_id\":279,\"country_id\":\"RO\",\"street\":[\"abc\"],\"telephone\":\"111\",\"postcode\":\"1111\",\"city\":\"def\",\"firstname\":\"azol\",\"lastname\":\"young\",\"default_billing\":true}],\"disable_auto_group_change\":0}");
    // has slashes still
    //return json_encode(json_decode($result), JSON_UNESCAPED_SLASHES);
    // this code will throw and expcetion:
    // Undefined property: *****\*****\Model\Mycustom::$_response
    //return  $this->_response->representJson(json_encode($data));
    return $result;
                
return json_encode($result, JSON_UNESCAPED_SLASHES);?$json_string = stripslashes($result)yreturn json_decode($json_string, true);Respuestas:
Podemos usar
json_encodeconJSON_UNESCAPED_SLASHES:fuente
stripslashes()función ojson_encode($str, JSON_UNESCAPED_SLASHES);?Cree ws.php en el directorio raíz de magento 2 y pegue el siguiente código en el archivo:
Después de esto, ejecute este archivo usando un enlace como http: //localhost/magento2/ws.php en el navegador y verifique la salida.
fuente
Intenté usar el siguiente script para probar si obtengo barras en la misma respuesta API:
Lo que produce esta respuesta (truncada por la función var_dump de PHP):
Como puede ver, no hay cortes en mi respuesta.
Así que te sugiero que tengas dos opciones:
str_replaceo similar.Una vez que tenga su respuesta sin barras, puede usar la siguiente línea para forzar a PHP a convertir la cadena en un objeto JSON:
fuente