Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery + JSON how to define key from variable

I have the following code

$.post(
    "/factory/set",{
         key : value
    },
    function(response) {

        });
    }, "json"
);

where

key = "foo"
value = "bar"

but the server always gets "key" and "bar", is there a way to set the key as variable, not string?

like image 596
Gessle Avatar asked Apr 07 '12 15:04

Gessle


People also ask

How to assign object keys as variable JavaScript?

Object keys can be dynamically assigned in ES6 by placing an expression in square brackets. Syntax: var key="your_choice"; var object = {}; object[key] = "your_choice"; console. log(object);

Can an object be a key in JSON?

JSON objects are written in key/value pairs. JSON objects are surrounded by curly braces { } . Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon.

Can you use variables in JSON?

Variables provide a new way to tackle different scenarios where JSON schema alone fails. This means, that you can use a new keyword named $vars to make your life easier.

What data type are the keys in JSON?

Keys must be strings, and values must be a valid JSON data type: string.


1 Answers

Create an object:

var data = {};

Then set the property:

data[key] = value;

Then use the object in your call to $.post():

$.post(
    "/factory/set",data,
    function(response) {

    }, "json"
);
like image 103
Anthony Grist Avatar answered Oct 06 '22 07:10

Anthony Grist