Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn HTML POST data into JSON?

  'recipient.firstName': 'Fred',
  'recipient.lastName': 'Johnson'

Is there any elegant way to turn this into:

var recipient = {
  firstName: 'Fred',
  lastName: 'Johnson
}

Using JS on the frontend? I want to POST JSON but it doesn't seem like that is done very easily with HTML, therefore I want to intercept the POST with jQuery and format it into the JSON I want.

EDIT: I am leaving the original question above for clarity's sake, but if you read closely you will see that the issue I have is not posting the data with AJAX to a REST API. That's very simple and already implemented. What is happening is that I am dynamically building forms using a template engine that I have created, and the forms id and names are built to represent nested data such as recipient.firstName. However, when I receive this data passed as JSON to the API endpoint, I need to transform it programatically from the first format to the second format, which is what the question is actually asking if you read it closely. Sorry for any confusion, the answer I have listed below solves the question.

like image 290
Anthony Avatar asked Nov 12 '15 23:11

Anthony


1 Answers

var recipient = [{firstName: "Fred",lastName: "Johnson"}]
                //:: CONVERT TO JSON
                recipient = JSON.stringify(recipient);
                //:: POST THE DATA 
                $.post(LINK_url,{post_recipient : recipient },json/*:: json not important, it can be auto guessed. delete ',json' */,function(output){
                    //var data =jQuery.parseJSON(output);});

______________________________edit_______________________________________

if i get you right this time your output is plan text and you need to convert to json, if so try this.

var recip = JSON.stringify[{ output }];
var data = jQuery.parseJSON(recip);
var viewdata='';
$.each(data, function(key, recipient){viewdata +=
recipient.firstName +" "+recipient.lastName+"<br/>"
})
prompt(viewdata);
like image 163
Timothy Nwanwene Avatar answered Oct 11 '22 01:10

Timothy Nwanwene