最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Best way to use JSON as a database? - Stack Overflow

programmeradmin1浏览0评论

I am creating an offline mobile web app, and am looking at using JSON to replicate some of my database tables and storing that in localStorage. (I am aware of Web SQL Database but it doesn't look particularly future-proof.)

I started with a very basic JSON output from the database, which looks a bit like this:

{
  "1": {"id":"1","name":"Hello","alias":"hello","category":"8"},
  "2": {"id":"2","name":"World","alias":"world","category":"3"},
  ...
}

However, there is a lot of data in many tables and space could be an issue with the constant repeating of field names. Storing the data like this halves the size:

{
  "1": ["1","Hello","hello","8"},
  "2": ["2","World","world","3"},
  ...
}

But now I have to reference a piece of data with a numeric index, possibly filling my code with magic numbers. I thought of storing an array like ["id","name"...] in another variable but the extra lookups seem like they would get messy.

Are there any practical ways to avoid that, but also keeping the Javascript code fairly neat? Any other useful strategies for this kind of development?

I am creating an offline mobile web app, and am looking at using JSON to replicate some of my database tables and storing that in localStorage. (I am aware of Web SQL Database but it doesn't look particularly future-proof.)

I started with a very basic JSON output from the database, which looks a bit like this:

{
  "1": {"id":"1","name":"Hello","alias":"hello","category":"8"},
  "2": {"id":"2","name":"World","alias":"world","category":"3"},
  ...
}

However, there is a lot of data in many tables and space could be an issue with the constant repeating of field names. Storing the data like this halves the size:

{
  "1": ["1","Hello","hello","8"},
  "2": ["2","World","world","3"},
  ...
}

But now I have to reference a piece of data with a numeric index, possibly filling my code with magic numbers. I thought of storing an array like ["id","name"...] in another variable but the extra lookups seem like they would get messy.

Are there any practical ways to avoid that, but also keeping the Javascript code fairly neat? Any other useful strategies for this kind of development?

Share Improve this question edited Apr 20, 2011 at 16:35 DisgruntledGoat asked Apr 20, 2011 at 15:35 DisgruntledGoatDisgruntledGoat 72.7k70 gold badges212 silver badges291 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

would it be possible to convert it into a format like this:

{
   id:{1:1, 2:2, ...},
   name:{1:hello, 2:world},
   alias:{1:hello, 2:world},
   category{1:8,2:3}
}

This way, you only store each column once, but you can still easily find things by their id.

JSON is not a database. JSON is a data interchange format.

Not sure if it would work across all mobile platforms, but XML would be an option.

发布评论

评论列表(0)

  1. 暂无评论