• Publicidad

Interpretar una respuesta JSON

¿Apenas comienzas con Perl? En este foro podrás encontrar y hacer preguntas básicas de Perl con respuestas aptas a tu nivel.

Interpretar una respuesta JSON

Notapor coltx » 2018-06-25 15:59 @708

Hola, amigos, tengo el siguiente script para capturar un endpoint en JSON.

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2.  
  3. use utf8::all;
  4. use JSON;
  5. use LWP::Simple;
  6. use Data::Dumper;
  7.  
  8.         my $ua = LWP::UserAgent->new;
  9.        
  10.         my $server_endpoint = "http://comercio.comerxxx.com/";                   #URL contains actual URL
  11.        
  12.         # set custom HTTP request header fields
  13.         my $req = HTTP::Request->new( GET => $server_endpoint );
  14.         $req->header( 'content-type' => 'application/json' );
  15.         $req->header( 'Accept'       => 'application/json' );
  16.         $req->header( 'secret'       => 'secreto' );
  17.         $req->header( 'dateDesde'       => '2018-06-10' );
  18.         $req->header( 'dateHasta'       => '2018-06-30' );
  19.        
  20.         my $response =  $ua->request($req)->as_string;
  21.        print $response;
  22.  
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4

Al ejecutar lo anterior recibo esto:

[{"Numero":100,"Fecha":"2018-01-01","CampoC":[]},{"Numero":200,"Fecha":"2018-01-02","CampoC":[]}]

Ahora bien, si cambio las últimas dos líneas por
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1.     my $response =  $ua->request($req);
  2.     my $data = decode_json($response);
  3.     print $data;
  4.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

recibo:

malformed JSON string, neither tag, array, object, number, string or atom, at character offset 0 (before "(end of string)") at GER_DATOS.pl line 29.

Entonces no sé cómo tomar los valores que me entrega el endpoint ya que al dejarlos como string no sé cómo interpretarlo y si lo trato de decodificar me arroja el error anterior. Favor, su ayuda para capturar la información que recibo desde esa API.

Gracias.
coltx
Perlero nuevo
Perlero nuevo
 
Mensajes: 79
Registrado: 2011-09-16 08:01 @376

Publicidad

Re: Interpretar una respuesta JSON

Notapor explorer » 2018-06-25 18:31 @813

El problema es que decode_json() está esperando un texto (codificado en UTF-8), pero lo que le estás pasando es un objeto HTTP::Response.

Creo que se te ha olvidado traducir la respuesta a texto, poniendo "->as_string", como tenías puesto en la línea 20 en el primer código (o dicho de otra manera: deja la línea 20 como estaba).

Y el resultado de decode_json() es una estructura de datos. Si haces un simple print(), no verás mucho.

Si quieres ver la forma de esa estructura, recuerda que Data::Dumper es tu amigo:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. use Data::Dumper;
  2. print Dumper($data);
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Interpretar una respuesta JSON

Notapor coltx » 2018-06-26 09:30 @438

explorer, al agregar las líneas como me dices:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. my $response =  $ua->request($req)->as_string;
  2. my $data = decode_json($response);
  3. use Data::Dumper;
  4. print Dumper($data);
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

recibo

malformed JSON string, neither tag, array, object, number, string or atom, at character offset 0 (before "HTTP/1.1 200 OK\nDat...") at ....

Si dejo solo lo siguiente:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. my $response =  $ua->request($req)->as_string;
  2. print $response;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

recibo lo siguiente, pero no sé cómo capturar la información.
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
HTTP/1.1 200 OK
Date: Tue, 26 Jun 2018 14:29:03 GMT
Server: Kesr
Content-Length: 136224
Content-Type: json/application
Client-Date: Tue, 26 Jun 2018 13:29:12 GMT
Client-Peer: 201.187.108.133:80
Client-Response-Num: 1
X-Powered-By: ASP.NET

[{"Numero":100,"Fecha":"2018-01-01","CampoC":[]},{"Numero":200,"Fecha":"2018-01-02","CampoC":[]}]
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4


Muchas gracias, explorer.
coltx
Perlero nuevo
Perlero nuevo
 
Mensajes: 79
Registrado: 2011-09-16 08:01 @376

Re: Interpretar una respuesta JSON

Notapor explorer » 2018-06-26 10:05 @462

Disculpas. He respondido de memoria.

A ver si con estas líneas te funciona:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. my $response = $ua->request($req);
  2. my $content  = $response->content;
  3. my $data = decode_json($content);
  4.  
  5. use Data::Dumper;
  6. print Dumper($data)
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España


Volver a Básico

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 0 invitados