0

I have a json object in my JavaScript file containing

"qs": {}

which when I store it in the database, becomes:

[object Object]

At other times the same object looks like this:

"qs":{"id": "stackoverflow"}

or this:

"qs":{"id": "stackoverflow", "location": "USA"}

But regardless of how many elements the array contains, I want to store it in a single database table field - so I need to compress it into a readable string.

What's the best way to do this with a field that may be null at certain times (as above)?

3 Answers 3

1

You probably want to use stringify to convert the object to a string.

Also {} is not null, it is an empty object. "qs" : null is null.

Sign up to request clarification or add additional context in comments.

Comments

1

You can convert it to its string representation (i.e. actual JSON; what you have there is an object literal, which is not the same as JSON) and use that. You can do this using JSON.stringify, falling back on one of the readily available alternatives.

Comments

0

The standard JSON functions will handle all of this transparently for you (including null and empty objects). When working with your data in JavaScript you should not work with the JSON string. Instead, first convert your the JSON from a string to a JavaScript variable. When you're ready to commit the data to the database again, convert it from a JavaScript variable to a JSON string again:

// initialise a variable with the string from the database
dbData = '{"id": "stackoverflow", "location": "USA"}';

// initialise a JavaScript object with the data from the database
jsData = JSON.parse(dbData);

// when ready to put the string back into the database convert the JS object to a string
dbDate = JSON.stringify(jsData);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.