Languages

JavaScript - encoding Object to JSON string

0 points
Asked by:
Dollie-Rutledge
806

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
Answered by:
Dollie-Rutledge
806

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

  1. JSON.stringify() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join