简体   繁体   中英

Storing a JSON object in a database

I am trying to store JSON data in a database but am having a hard time figuring out the best way to do this with MySQL.

{
"id":"9",
"title":"title",
"images":[
{
"image":"house.png",
"width":"680",
"height":"780"
},{
"image":"car.png",
"width":"680",
"height":"780"
},{
"image":"dog.png",
"width":"680",
"height":"780"
}
],
"date":"1338418777"
}

So of course it is no problem to have a table with field names of id,title and date. But for 'images' it seems I would have to have a separate table with a relational setup.

That is ok maybe for this example where things are kind of simple but what about objects with many arrays and multiple tiers of information.

Is there some way to approach this that doesn't lead to a very complex database?

It is always a good practice to have images in a different tables along with a relationship..

Suppose you have and event photos module to make.. It is a good practice to add the event without the photos in the events table and make another table named eventPhotos that will have fields like (id, event_id, title, YOUR OTHER FIELDS) .

Finally when you need to retrieve them, simply make 2 database calls and arrange the output json as you need..

This will allow you to handle the json object's key 'images' array pretty well and things will remain more simple and classified.

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