【问题标题】:How to import json file into indexeddb?如何将json文件导入indexeddb?
【发布时间】:2015-10-20 14:37:25
【问题描述】:

我正在做一个在 IndexedDB 中存储一些数据的应用程序,但我想先加载一些我的 json 文件中的数据。

这是我的 json 文件:

{
  "ciudades":[
    {
      "ciudad":"Asuncion",
      "latitud":-25.2985296,
      "longitud":-57.6710677
    },
    {
      "ciudad":"Caaguazu",
      "latitud":-25.465034,
      "longitud":-56.0183859
    },
    {
      "ciudad":"Ciudad del Este",
      "latitud":-25.4933441,
      "longitud":-54.6710438
    },
     {
      "ciudad":"San Pedro",
      "latitud":-24.1586759,
      "longitud":-56.636503
    },
     {
      "ciudad":"Pedro Juan Caballero",
      "latitud":-22.5450875,
      "longitud":-55.7618963
    }
 ]
}

【问题讨论】:

  • 你能提供json字符串,这样对我们有帮助吗?
  • 您对哪一部分有问题?将 json 放入对象或将对象存储到 IndexedDB 对象存储中?你的 json 文件在哪里?在服务器还是客户端?
  • 我可以将 json 放入一个对象并显示在视图中。但问题是如何将该对象存储在 indexedDB 中。我的文件在客户端
  • 发布您尝试过的代码以及您遇到的错误。如果您因为不了解 IDB 而还没有尝试过任何东西,也许可以从这里的示例开始developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/…

标签: json indexeddb


【解决方案1】:

你跟着步骤

步骤 1 read mozilla site

第二步创建索引数据库

var ciudades = [
{
  "ciudad":"Asuncion",
  "latitud":-25.2985296,
  "longitud":-57.6710677
},
{
  "ciudad":"Caaguazu",
  "latitud":-25.465034,
  "longitud":-56.0183859
},
{
  "ciudad":"Ciudad del Este",
  "latitud":-25.4933441,
  "longitud":-54.6710438
},
 {
  "ciudad":"San Pedro",
  "latitud":-24.1586759,
  "longitud":-56.636503
},
 {
  "ciudad":"Pedro Juan Caballero",
  "latitud":-22.5450875,
  "longitud":-55.7618963
}
];

var IDBSetting = {
    name: "indexedDBName",
    version: 1,
    tables: [{
        tableName: "ciudades",
        keyPath: "seq",
        autoIncrement: true,
        index: ["ciudad", "latitud", "longitud],
        unique: [false, false, false]
    }]
};

! function() {
    console.log("indexeDB init");

    var req = indexedDB.open(IDBSetting.name, IDBSetting.version);

    req.onsuccess = function(event) {
        console.log("indexedDB open success");
    };

    req.onerror = function(event) {
        console.log("indexed DB open fail");
    };

    //callback run init or versionUp
    req.onupgradeneeded = function(event) {
        console.log("init onupgradeneeded indexedDB ");
        var db = event.target.result;

        for (var i in IDBSetting.tables) {
            var OS = db.createObjectStore(IDBSetting.tables[i].tableName, {
                keyPath: IDBSetting.tables[i].keyPath,
                autoIncrement: IDBSetting.tables[i].autoIncrement
            });

            for (var j in IDBSetting.tables[i].index) {
                OS.createIndex(IDBSetting.tables[i].index[j], IDBSetting.tables[i].index[j], {
                    unique: IDBSetting.tables[i].unique[j]
                });
            }
        }
    }
}();

第三步添加数据

var IDBFuncSet = {
    //write
    addData: function(table, data) {
        var req = indexedDB.open(IDBSetting.name, IDBSetting.version);

        req.onsuccess = function(event) {
            try {
                console.log("addData indexedDB open success");
                var db = req.result;
                var transaction = db.transaction([table], "readwrite");
                var objectStore = transaction.objectStore(table);
                var objectStoreRequest = objectStore.add(data);
            } catch (e) {
                console.log("addDataFunction table or data null error");
                console.log(e);
            }

            objectStoreRequest.onsuccess = function(event) {
                //console.log("Call data Insert success");
            }
            objectStoreRequest.onerror = function(event) {
                console.log("addData error");
            }
        };

        req.onerror = function(event) {
            console.log("addData indexed DB open fail");
        };
    }
}

for(var i in ciudades){
   IDBFuncSet.addData("ciudades",ciudades[i]);
}

步骤 4 获取数据

IDBFuncSet.getAllData = function(arr, table) {
    try {
        var req = indexedDB.open(IDBSetting.name, IDBSetting.version);

        req.onsuccess = function(event) {
            var db = req.result;
            var transaction = db.transaction([table], "readonly");
            var objectStore = transaction.objectStore(table);

            var objectStoreRequest = objectStore.openCursor();

            objectStoreRequest.onsuccess = function(event) {
                var cursor = event.target.result;
                if (cursor) {
                    arr.push(cursor.value);
                    cursor.continue();
                } else {

                }
            }
        };
        req.onerror = function(event) {
            console.log("getAllData indexed DB open fail");
        };
    } catch (e) {
        console.log(e);
    }
}
var ciudadesArr = [];
IDBFuncSet.getAllData(ciudadesArr, "ciudades");

console.log(ciudadesArr);

希望对你有帮助

【讨论】:

    【解决方案2】:

    这是我的做法,thanks to the android-indexeddb 包。

    angular.module('yourApp', ['indexedDB'])
        .config(function($indexedDBProvider) {
            $indexedDBProvider
                .connection('dbName')
                .upgradeDatabase(1, function(event, db, tx) {
                    var objStore = db.createObjectStore('storeOne', { keyPath: 'stop_id' });
                    objStore.createIndex('store_id', 'store_id', { unique: false });
                })
                // the next upgradeDatabase() function is necessary if you 
                // wish to create another datastore
                .upgradeDatabase(2, function(event, db, tx) {
                    var secondObjectStore = db.createObjectStore('storeTwo', { keyPath: 'my_id' });
                    secondObjectStore.createIndex('another_id', 'another_id', { unique: false });
                });
        })
    

    然后在我的控制器中:

    angular.module('yourApp')
        .controller('homeCtrl', ['$scope', '$http', '$indexedDB', function($scope, $http, $indexedDB) {
            $scope.objects = [];
            var loadJSON = function(file_name) { ... //load the json file in here}
    
            $indexedDB.openStore('storeOne', function(store) {
                var loaded = loadJSON('file_name.json');
                store.upsert(loaded).then(function(e) {
                    console.log('added successfully');
                });
            });        
    
            $indexedDB.openStore('times', function(store) {
                var loaded = loadJSON('file_name.json');
                store.upsert(loaded).then(function(e) {
                    console.log('added successfully');
                });
            });
        }]);
    

    查看项目页面以了解有关此软件包的更多技巧。

    虽然这个 angular-indexeddb 页面支持查询,但对于连接等高级查询,您可能想要consider ydn-db

    使用这两个包获得一些非常好的工作流程。

    对于 loadJSON() 函数,它可能是这样的:

    var loadJSON = function(file_name) {
        var data;
        $.ajax({
            url: '../data/' + file_name,
            dataType: 'json',
            async: false,
            success: function(res_data) {
                data = res_data;
                console.log('Loaded ' + file_name + ' nicely');
            },
            error: function(err) {
                console.log('error happened');
            }
        });
        return data;
    }
    

    【讨论】:

      【解决方案3】:

      File API,但这似乎还不是一个可靠的标准。

      我现在要做的是让用户打开文件,将其内容复制到剪贴板,然后将其粘贴到我网页上的 TextArea 元素中。

      在 JavaScript 中,我为 TextArea 的更改事件添加了一个侦听器,并将文本内容解析为 JSON,然后将其写入 indexedDB。

      【讨论】:

        猜你喜欢
        • 2018-04-10
        • 2021-02-18
        • 2014-02-22
        • 2017-01-06
        • 2015-02-26
        • 2019-09-01
        • 2015-10-13
        • 2013-07-25
        • 2018-12-25
        相关资源
        最近更新 更多