EN
JavaScript - encoding Object to JSON string
1
answers
0
points
I have a problem with encoding an object into a JSON string.
My Object looks like this:
items[a]['item_id'] = 1;
items[a]['user_id'] = 2;
items[a]['data']['color'] = 'red';
items[a]['data']['description'] = 'item description';
Now, I want to get it into a JSON string to put it into AJAX request.
{
'a': {
'item_id': 1,
'user_id': 2,
'data': ...
}
}
How can I do this?
1 answer
0
points
What is causing the bug in your code is probably the variable a, make sure it is defined.
Then you can use JSON.stringify() method to create the JSON string for AJAX request.
Practical example
// ONLINE-RUNNER:browser;
var items = {};
items.a = {};
items.a.data = {};
items.a.item_id = 1;
items.a.user_id = 2;
items.a.data.color = 'red';
items.a.data.description = 'item description';
var json = JSON.stringify(items); // creates JSON string
console.log(json);
result:
{
"a": {
"data": {
"color": "red",
"description": "item description"
},
"item_id": 1,
"user_id": 2
}
}
References
0 comments
Add comment