Search code examples
jquerystringify

JSON Object from TextAreas


Im not sure if Im on the right path, but I want to convert text from the text areas to JSON Object.

The payload should look like this.

{
"intent":"SanFransico",
   "examples":[
    {
        "text":"San Fran"
    },
    {
        "text":"Bay Area"
    }
     ]
}

What I can do at the moment is sending in this textareas

   <textarea name="intent[intent]">SanFransico</textarea>
   <textarea name="intent[examples][text]">San Fran</textarea>
   <textarea name="intent[examples][text]">Bay Area</textarea>

unfortunately The payload that returns looks like this, and it does not return the second text field.

{
   "intent":
   {
    "intent":"SanFransico",
     "examples":{
         "text":"Bay Area"
     }
   }
}

I have a fiddler Im experimenting whit. https://jsfiddle.net/8w4tx1pk/

Any ideas if this is the right path? or do I need a more complicated function?


Solution

  • After fixing up your fiddle, I was able to address it.

    Fiddle: https://jsfiddle.net/Twisty/8w4tx1pk/11/

    HTML

    <div class="container">
      <form id="my-profile">
        <textarea name="intent">San Francisco</textarea>
        <textarea name="examples[][text]">San Fran</textarea>
        <textarea name="examples[][text]">Bay Area</textarea>
        <div class="clearfix">
          <button type="button" id="btnSerialize" class="btn btn-primary pull-right">serializeToJSON</button>
        </div>
    
        <div class="form-group">
          <textarea id="result" class="form-control" rows="10"></textarea>
        </div>
      </form>
    </div>
    

    JavaScript

    $(function() {
      $("#btnSerialize").on("click", function() {
    
        var obj = $('#my-profile').serializeJSON();
        console.log(obj);
    
        var jsonString = JSON.stringify(obj);
        $("#result").val(jsonString);
      })
    });
    

    Result

    {
      "intent":"San Francisco",
      "examples":[
        {
          "text":"San Fran"
        },{
          "text":"Bay Area"
        }
      ]
    }