我正在尝试格式化一个巨大的js文件,所以我可以将它插入一个MongoDB集合并通过AJAX读取它,但我的语法有问题。它是这样的:
var MyVariable1 = [ {
ThingsToGet: [
{
first_thing: "SOMETHING ONE",
second_thing: [[1, 0], [2, 0], [3, 4], [4, 4], [5, "x"], [6, "x"]]
third_thing: 0,
fourth_thing: []
},{
first_thing: "SOMETHING TWO",
second_thing: [[1, 0], [2, 5], [3, 4], [4, 4], [5, "x"], [6, "x"]],
third_thing: 0,
fourth_thing: []
},{
first_thing: "SOMETHING THREE",
second_thing: [[1, 0], [2, 0], [3, 4], [4, 4], [5, 2], [6, 2]],
third_thing: 0,
fourth_thing: []
},
]
}
];
var MyVariable2 = [ {
ThingsToGet: [ etc, etc, etc...
我打算用PHP查询它:
$variable_to_send_to_jquery = "MyVariable1";
$filter = array(
'var'=>"MyVariable1";
);
$results = $collection->findone($filter);
答案 0 :(得分:1)
我建议如果这是一次性的事情,你得到Node.JS安装并使用如下代码,如果你有很多预先存在的JSON类文件要加载(你有的语法)实际上是JavaScript)。虽然我不理解你的数据模型(并且稍微改变了它以便编译),但基本上我所做的只是创建一个包含你添加的所有“变量”数组的变量。
通过将它们放在一个数组中,您可以调用MongoDB的insert
方法一次插入一大批文档。回调是文档(设置了_id
字段)。如果您有数千个文档,则可能需要使用JavaScript的数组slice
将数组拆分为较小的块,这样就不会导致驱动程序超时时出现非常大的insert
。
var mongo = require('mongodb').MongoClient
, Server = require('mongodb').Server;
var allVariables = [ {
ThingsToGet: [
{
first_thing: "SOMETHING ONE",
second_thing: [[1, 0], [2, 0], [3, 4], [4, 4], [5, "x"], [6, "x"]],
third_thing: 0,
fourth_thing: []
},{
first_thing: "SOMETHING TWO",
second_thing: [[1, 0], [2, 5], [3, 4], [4, 4], [5, "x"], [6, "x"]],
third_thing: 0,
fourth_thing: []
},{
first_thing: "SOMETHING THREE",
second_thing: [[1, 0], [2, 0], [3, 4], [4, 4], [5, 2], [6, 2]],
third_thing: 0,
fourth_thing: []
},
]
}
,
{
ThingsToGet: [
{
first_thing: "SOMETHING ONE",
second_thing: [[1, 0], [2, 0], [3, 4], [4, 4], [5, "x"], [6, "x"]],
third_thing: 0,
fourth_thing: []
},{
first_thing: "SOMETHING TWO",
second_thing: [[1, 0], [2, 5], [3, 4], [4, 4], [5, "x"], [6, "x"]],
third_thing: 0,
fourth_thing: []
},{
first_thing: "SOMETHING THREE",
second_thing: [[1, 0], [2, 0], [3, 4], [4, 4], [5, 2], [6, 2]],
third_thing: 0,
fourth_thing: []
},
]
}
];
mongo.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('variables');
// you may want to do them in batches rather than all at once
collection.insert(allVariables, function(err,docs){
if(err) throw err;
if(docs) {
console.log("Docs inserted: " + docs.length)
// you could do something here with the docs
}
});
});
另一种选择是在PHP中实际使用json-decode
(docs)功能来加载JSON,然后使用MongoDB PHP驱动程序插入文档。您需要将JSON文件的语法更改为纯JSON。例如,它不能在文件中包含变量声明。
它可能会是这样的:
$bigJsonFile = file_get_contents('./variables.json', false)
$bigJsonObject = json_decode($json)
$collection->insert($bigJsonObject)