简体   繁体   中英

How to create complex javascript object for JSON API

Below is the structure of JSON which I use to query an API

"order_items": [
        {
            "menu_item_id": "VD1PIEBIIG", 
            "menu_item_name": "Create Your Own", 
            "modifiers": [
                {
                    "modifier_id": "6HEK9TXSBQ", 
                    "modifier_name": "Shrimp"
                }
            ], 
            "quantity": "1", 
            "total": 15.99, 
            "variant_id": "TXDOR7S83E", 
            "variant_name": "X-Lg 18\""
        }
    ]

Now I want to call this API from an HTML page using Javascript(Using HTML elements like forms and drop down menus etc). I want to create a Javascript object with proper structure and then convert it to JSON using "stringify" function. But I am not able to create the Javascript object. Can anyone help with this?

Like i want to have the following structure

obj.order_items[0].menu_item_id="VD1PIEBIIG";
obj.order_items[0].menu_item_name="Create Your Own";
obj.order_items[0].modifiers[0].modifier_id="6HEK9TXSBQ";

and so on.

var jsonToSend = { "order_items": [ ] };

// then for each order item
var orderItem = { "menu_item_id": <whatever>, 
  "menu_item_name": <whatever>,
  "quantity": <whatever>,
  "total": <whatever>,
  "variant_id": <whatever>,
  "variant_name": <whatever>,
  "modifiers": []
};

// then for each modifier
var modifier = { "modifier_id": <whatever>, "modifier_name": <whatever> };
orderItem.modifiers.push(modifier);

jsonToSend.order_items.push(orderItem);

JSON.stringify(jsonToSend);

Well there are a couple of ways to do this.

  • Manually create the Json object to send from the HTML elements:

      $.ajax({ type: "POST", url: "some.php", data: new {"order_items": [ { "total": $('total').Val(), "variant_id": $('variant_id').Val(), "variant_name": $('variant_name').Val() } ]}) .done(function( msg ) { alert( "Data Saved: " + msg ); }); 
  • You could use a great framework like KnockoutJs , this will keep your JSON object up to date with your form, so that you don't have to do it manually. When you are ready you just submit your original json back to the server.

See this basic example on JsFiddle

    var ClickCounterViewModel = function() {
    this.numberOfClicks = ko.observable(0);

    this.registerClick = function() {
        this.numberOfClicks(this.numberOfClicks() + 1);
    };

    this.resetClicks = function() {
        this.numberOfClicks(0);
    };

    this.hasClickedTooManyTimes = ko.computed(function() {
        return this.numberOfClicks() >= 3;
    }, this);
};

ko.applyBindings(new ClickCounterViewModel());
  • You can use any number of plugins to Serialize the form, but the problem is getting the JSON structure just right.

See SerializeArray

$( "form" ).submit(function( event ) {
      console.log( $( this ).serializeArray() );
      event.preventDefault();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM