I have a web request that is sending the server data that is in the format application/x-www-form-urlencoded
. I would like to convert it to application/json
.
Example:
URL-encoded form data:
Property1=A&Property2=B&Property3%5B0%5D%5BSubProperty1%5D=a&Property3%5B0%5D%5BSubProperty2%5D=b&Property3%5B1%5D%5BSubProperty1%5D=c&Property3%5B1%5D%5BSubProperty2%5D=d
Pretty version:
Property1=A Property2=B Property3[0][SubProperty1]=a Property3[0][SubProperty2]=b Property3[1][SubProperty1]=c Property3[1][SubProperty2]=d
The above data needs to be converted to the following JSON data:
{ Property1: "A", Property2: "B", Property3: [ { SubProperty1: "a", SubProperty2: "b" }, { SubProperty1: "c", SubProperty2: "d" }] }
Question:
Are there any free tools that are capable of doing this? I have not been able to find any myself and if they exist, I'd rather consume them than writing one myself, but if it comes to that, I will.
A C#/.Net solution is preferred.
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.
var obj = $('form'). serializeJSON(); var jsonString = JSON. stringify(obj);
I've written a utility class for parsing query strings and form data. It's available at:
https://gist.github.com/peteroupc/5619864
Example:
// Example query string from the question String test="Property1=A&Property2=B&Property3%5B0%5D%5BSubProperty1%5D=a&Property3%5B0%5D%5BSubProperty2%5D=b&Property3%5B1%5D%5BSubProperty1%5D=c&Property3%5B1%5D%5BSubProperty2%5D=d"; // Convert the query string to a JSON-friendly dictionary var o=QueryStringHelper.QueryStringToDict(test); // Convert the dictionary to a JSON string using the JSON.NET // library <http://json.codeplex.com/> var json=JsonConvert.SerializeObject(o); // Output the JSON string to the console Console.WriteLine(json);
Let me know if it works for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With