我有一些日志文件,其中包含以下样本数据。该文件是使用其他程序生成的,它会将这些行附加到文件中。
{ 'Temperature' : 53.375 }, { 'Timestamp' : 1416429462 }
{ 'Temperature' : 53.385 }, { 'Timestamp' : 1416459464 }
.
.
and so on...
好吧,我写了这样的东西来获取价值。这只是一个例子
var result =[{ 'Temperature' : 53.375 }, { 'Timestamp' : 1416429462 }];
$.each(result, function(k, v) {
for(var attribute in v){
if(v.hasOwnProperty(attribute)){
alert(attribute + ' is ' + v[attribute]);
}
}
});
我的问题是如何逐行读取文件并从中生成JSON输出? 输出应该看起来像这样
{
"city": [
{
"Temperature": 53.375,
"Timestamp": 1416429462
},
{
"Temperature": 53.385,
"Timestamp": 1416459464
}
]
}
我对JQuery没有多少经验,所以老实说我不知道如何处理这个问题。
答案 0 :(得分:1)
您可以将其转换为多维数组格式,并使用JSON.stringify将其格式化为json
var result =[{ 'Temperature' : 53.375 }, { 'Timestamp' : 1416429462 }];
var data = {"city" : result};
var json = JSON.stringify(data);
alert(json);
答案 1 :(得分:1)
这有点脏,但值得尝试。适用于您的情况
//Assuming this is the content of the file
var q = "{ 'Temperature' : 53.375 }, { 'Timestamp' : 1416429462 }{ 'Temperature' : 53.385 }, { 'Timestamp' : 1416459464 }"
q = replaceAll(q,"'","\"");
q = replaceAll(q,"}, {",",");
q = replaceAll(q,"}{","},{");
//Instead of above line you may have to try this below variation. Which considers a new line character
q = replaceAll(q,"}\n{","},{");
q = "{\"City\":["+q+"]}";
//An alert for you to see what your string looks like now
alert(q);
// this is the final Json object
var result = $.parseJSON(q)
function replaceAll(str, find, replace) {
var i = str.indexOf(find);
if (i > -1){
str = str.replace(find, replace);
i = i + replace.length;
var st2 = str.substring(i);
if(st2.indexOf(find) > -1){
str = str.substring(0,i) + replaceAll(st2, find, replace);
}
}
return str;
}