lara336223's avatar

json_encode()

Building this System, I have got some code from another coder & they have used json_encode() Would you say this is good for storing Data in a MySql Field ? Or should I change it to use more fields ?

0 likes
4 replies
JussiMannisto's avatar

It's almost always better to have separate columns in a relational database. The cases where you'd want a JSON column are rare and very specific.

But you shouldn't make changes just based on rules of thumb. If you think it's a bad idea in your specific case, then change it. If you need to query fields within the JSON column, you need to do some tricks to index the fields. In that case JSON is likely a bad choice. But if you need to store some complicated JSON document that you only ever need access in the context of that model, then JSON is probably fine.

2 likes
jdc1898's avatar

To expand on what @jussimannisto said. It’s not an easy yes or no question. If for example you have some metadata that you want to retrieve about a model for example. Storing the data in a key value pair may be completely correct. If you’re going to access the data frequently, put it in a column. If you’re simply going to enrich the model with supplemental data, JSON column is perfectly fine.

1 like
vincent15000's avatar

@jdc1898

If you’re simply going to enrich the model with supplemental data, JSON column is perfectly fine.

But if you need to index these data, it's not a good idea.

1 like
jdc1898's avatar

@vincent15000 Agreed. I'm simply saying there are use cases and only the developer will likely know when/if JSON data is a good idea.

1 like

Please or to participate in this conversation.