简体   繁体   English

在数据库中存储json的正确方法

[英]Proper way to store json in database

Does json usually have enclosing quotation marks when stored in a database field? 将json存储在数据库字段中时,通常是否带有引号?

Which of the following would be correct for the json column? 以下哪个对json列正确?

`json`
'{"Color": "Red"}'
 {"Color": "Red"}

My assumption would be the second, but just wanted to make sure that's correct. 我的假设是第二个,但只是想确保它是正确的。 And if so, why? 如果是这样,为什么?

As of MySQL 5.7.8, MySQL supports a native JSON data type 从MySQL 5.7.8开始,MySQL支持本机JSON数据类型

If you use earlier version and store it as text, store it without the enclosing quotation marks. 如果您使用早期版本并将其存储为文本,请在存储时不使用引号引起来。

While it is possible to store the data as you suggest, it would be better to store the data in a table named json with field color then insert two records, each containing the value 'red'. 尽管可以按照您的建议存储数据,但最好将数据存储在具有字段color名为json的表中,然后插入两个记录,每个记录包含值“ red”。

It's more work now, because it involves deconstructing and reconstructing the JSON, but it saves work later if you need to serve the data in some format other than JSON, then you won't need to reformat all of the data in your database. 现在需要做更多的工作,因为它涉及解构和重建JSON,但是如果您需要以JSON以外的其他格式提供数据,则可以节省以后的工作,那么您就不需要重新格式化数据库中的所有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM