Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Perl json parser and JSONP issue

by heatblazer (Scribe)
on Jun 15, 2012 at 12:44 UTC ( #976424=perlquestion: print w/ replies, xml ) Need Help??
heatblazer has asked for the wisdom of the Perl Monks concerning the following question:

I`ve just ended serilizing some test data into a json with perl script using JSON from CPAN ( one of many ). It is working but: I have a problem or rather to say confusion. Let me show you:

#!/opt/lampp/bin/perl use CGI; use JSON; use utf8; ##### S U B S ######### sub speaker { my $text = shift; print "Content-type: text/html\n\n"; print $text; } ###################################################### #Extracts contents from JSON file, no extra mods required sub extract_json { my $file = shift; my $jobject = ""; open ( FH, "< $file") || die "Can`t open file: $!\n"; while ( <FH> ){ $jobject .= $_; } close FH or die "Can`t close FH: $!\n"; return $jobject; } #################################################### sub record { my ($name, $mail, $pass, $file) = @_; if ( $name && $mail && $pass ) { my $fromj = extract_json($file); #all well to here my $json = decode_json($fromj); print $json[0]->[0]{"name"}; } } ################################################### my $jobj = extract_json("dat.json"); my $perl_data = decode_json($jobj); my $jobject = encode_json($perl_data); my @perl_data2 = decode_json($jobject); my $len = @perl_data2; print "Size of perl_data2 is $len \n"; $perl_data2[0]->[6] = {"name","boho", "age",31, "id",987654 }; $perl_data2[0]->[5]={"name","dodo", "age",31, "id", 987654 }; $perl_data2[0]->[4] ={"name","pupo", "age",31, "id", 987654 }; $perl_data2[1]->[0] ={"ver",2222, "beta" ,"yes", "id", 987654 }; $jobject = encode_json($perl_data2[0]); open(FH, ">df.json"); print FH $jobject; close(FH); for ( $i=0; @perl_data2->[0][$i]; $i++ ) { print $perl_data2[0]->[$i]{"name"}, "\n"; }

So... my questions are:

  1. Why there is a 2d array? My json is a single dimension array with just 3 objects ( converted to perl corectly )
  2. How to extract array size in my case? I`ve tried to bind a var like $my var = @perl_data2[0] which is supposed that I want to refer to an array but it is not working.

That is for PERL. If you are JSON expert read below please

JSONP experts only

I have and a json question if there are JSONP experts

I`ve followed some advanced topics on this but I still can`t get it to work

Here is my javascript code if you can evaluate it and tell me where is my mistake

window.onload = function() { // some code here dbg("Window loaded..."); document.getElementById('send').onclick = sendForm; document.getElementById('show').onclick= setRefresher; //document.getElementById("jsonp").onload = showData; document.getElementById("delete").onclick = function() { var father = document.getElementById('text'); if ( father.children ) { killKid(father); } }; }; // Debugger function ///////////////////////////////////////////////// +//////////////////////////////////////////////////////// function dbg(text) { console.log(text[0].name); } // make children and append them to father function makeKid(type, data, father) { var kido = document.createElement(type); kido.innerHTML = data; father.appendChild(kido); } //flush all childrem function killKid(father) { //father.removeChild(father.children[0]); for ( var i=father.children.length-1; i >= 0; i-- ) { father.removeChild(father.children[i]); } } ////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// /* var showData = function (data) { console.log("showData() called"); var div = document.getElementById('text'); if ( ! div.children[0] ) { for ( var i=0; i < data.length; i++ ) { console.log(i); makeKid("p", data[i].name, div); makeKid("p", data[i].id, div); makeKid("p", data[i].age, div); } } } */ /*000000000000000000000000000000000000000000000000000000000000000000*/ function setRefresher() { dbg("setRefresher called"); var rnd = "&rnd="+Math.floor(Math.random() * 12345); var dat = "&time="+new Date().getTime(); var url = "http://localhost/dat.json?callback=dbg"; var newScript = document.createElement('script'); newScript.setAttribute('src', url); newScript.setAttribute('id', 'jsonp'); var head = document.getElementsByTagName('head')[0]; if ( !document.getElementById('jsonp') ) { head.appendChild(newScript); dbg("setRefresher 1st option"); } else { var oldOne = document.getElementById('jsonp'); head.replaceChild(newScript, oldOne); dbg("setRefresher 2nd option"); } } /********************************************************************* +******************************************/ function sendForm() { var name = document.getElementById('name').value; var mail = document.getElementById('mail').value; var pass = document.getElementById('pass').value; if ( name && mail && pass ) { var url = "http://localhost/serv.pl?name="+name+"&mail="+m +ail+"&pass="+pass+"&rnd="+Math.floor(Math.random()*12345)+"&dat="+new + Date().getTime(); var form = document.getElementById('form'); form.method = "get"; form.action = url; form.submit(); //window.location.replace(url); } else { // none } }

I have a validated JSON file form JSON Lint which is:

[ { "name": "gosho", "age": 33, "id": 627362 }, {"name": "ilian", "age": 31, "id": 87637 }, {"name": "hr-isto", "age": 31, "id": 1234 }, {"name": "petzata", "age": 31, "id": 83843 } ]

Can you tell me why that callback is not working and why not passing it to console log? I `ve viewed it in firebug and the JSON is loaded in script into the head. Please help.

Comment on Perl json parser and JSONP issue
Select or Download Code
Re: Perl json parser and JSONP issue
by tobyink (Abbot) on Jun 15, 2012 at 14:04 UTC

    Not looked at your first problem, but as far as your second problem goes, it appears you are loading a JSON file where a JSONP file is expected. JSON and JSONP are different file formats!

    • JSON is a data format (like e.g. XML or YAML);
    • JSONP is an executable Javascript script, typically produced to follow certain conventions.
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      I know that, so that`s why I posted my javascript code. You can clearly see that I am passing a JSON file to a callback function, as I followed 2 examples. I just get nothing. When I press the button ( who executes the JSONP creation ) it`s ok, in firebug I do see the json object clearly, it is in the DOM but nothing more.. Most examples say that this must work fine.

        "You can clearly see that I am passing a JSON file to a callback function"

        Yes - that's entirely the problem. Your function expects to be get JSONP, and it's being given JSON. As I said: JSON and JSONP are different file formats.

        You script is trying to get some JSONP from http://localhost/dat.json?callback=dbg but it's being given JSON. JSON and JSONP are different file formats.

        Here's an example JSON file:

        { "name": "Joe Bloggs" }

        Here's an example JSONP file:

        process({ "name": "Joe Bloggs" });

        As you can see, they look a little bit different. That's because JSON and JSONP are different file formats.

        Also, make sure you're sending the correct HTTP headers.

        • For JSON, you want Content-Type: application/json.
        • For JSONP, you want Content-Type: application/ecmascript or Content-Type: application/javascript or Content-Type: text/javascript.

        Note the difference: that's because JSON and JSONP are different file formats.

        perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://976424]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2014-07-10 03:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (198 votes), past polls