0

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.

2

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Hello, I tried your answer and the snippet works just fine, However it does not work in my case. So as I mentioned the function which I am using to get the form data, I get the form data as : "'{\"subject\":\"school,\",\"description\":\"top10,\",\"classsize\":\"35\"}'" Is this why solution is not working for me? when I do a console.log, it shows me string in format, you have stated. Please help me out if possible.
@newbietocoding Yes, that isn't a valid JSON string. You need to reformat it. See my edit
@newbietocoding Actually my changes didn't save. I've saved them now, see my edits

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.