简体   繁体   中英

How to represent a nullable json object as a single string?

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)?

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.

You can convert it to its string representation (ie 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.

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);

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