Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you send JSON through a url?

I have a ruby hash where the keys are urls and the values are integers. I convert the hash to JSON and I'm wondering if I'll be able to send the JSON inside a url via an AJAX request and then pull that JSON from a params hash.

Also, I am going to be sending a JSONifyed ruby hash back to the client. If I have a success callback in my AJAX function where I receive the data in a data variable, how do I parse that JSON with JQuery?

Please let me know if I need to be more specific.

like image 843
Justin Meltzer Avatar asked Jul 08 '11 20:07

Justin Meltzer


People also ask

How can I get JSON data from URL?

Output: In this way, one can easily read a JSON response from a given URL by using urlopen() method to get the response and then use json. loads() to convert the response into a JSON object.

How pass JSON object in HTTP GET?

To get JSON from a REST API endpoint, you must send an HTTP GET request and pass the "Accept: application/json" request header to the server, which will tell the server that the client expects JSON in response.

How do you pass a JSON object into a URL in Python?

To post a JSON to the server using Python Requests Library, call the requests. post() method and pass the target URL as the first parameter and the JSON data with the json= parameter. The json= parameter takes a dictionary and automatically converts it to a JSON string.

Can JSON be streamed?

JSON streaming comprises communications protocols to delimit JSON objects built upon lower-level stream-oriented protocols (such as TCP), that ensures individual JSON objects are recognized, when the server and clients use the same one (e.g. implicitly coded in).


1 Answers

Yes, you can with no problem. No manual encoding/decoding needed!

Your code would be like this:

var jsonParam = '{"name":"Edgar"}'; //Sample json param
$.ajax({
  ...  
  type: "get", //This sends in url
  data: {jsonParam: jsonParam}, //This will encode your json for url automatically
  dataType: "json", //With this the response will be automatically json-decoded!
  success: function(response){ //Assuming your server output was '{"lastName":"Villegas"}' as string
     alert(response.lastName);
  }
});

As you can see, no manual encoding/decoding was needed. Jquery handles it all!

Hope this helps. Cheers

PS: If, for some reason, you need to encode/decode your json manually for url use javascript's encodeURIComponent(string) and $.parseJSON(jsonString) methods.

like image 91
Edgar Villegas Alvarado Avatar answered Sep 28 '22 19:09

Edgar Villegas Alvarado