newbietocoding
newbietocoding

Reputation: 65

Convert a JSON string to a JSON object (Not java script Object)

I need to convert a string into a JSON object so that I can post it using AJAX. As of now, all the answers I could find were converting it to javascript objects due to which there were no double quotes on the 'keys' and had double quotes only on the values. I have searched a lot, but almost all the answers convert it to a JS object, and the REST endpoint will only accept JSON object. Please help.

I have a string in this format:

{"subject":"school,","description":"top10,","classsize":"35"}

Function to get form data as JSON string

function getFormData($form){
     var unindexed_array = $form.serializeArray();
     var indexed_array = {};

     $.map(unindexed_array, function(n, i){
      indexed_array[n['name']] = n['value'];
                    });

                    return indexed_array;
                }

and then I use JSON.stringify on the form data.

Upvotes: 0

Views: 538

Answers (1)

symlink
symlink

Reputation: 12208

Use JSON.parse():

var string = "'{\"subject\":\"school,\",\"description\":\"top10,\",\"classsize\":\"35\"}'";
//remove the backslashes
var string_ed = unescape(string);
//remove the surrounding single quotes
string_ed = string_ed.substr(1, string_ed.length - 2);
var jsonObj = JSON.parse(string_ed);

document.getElementById("result").innerText = JSON.stringify(jsonObj);
<div id="result"></div>

Upvotes: 2

Related Questions