我需要使用JAVA脚本生成一个JSON文件,但是没有得到预期的输出,你能不能帮助我生成这个。
预期结果:
{
"ewh5yuwe": {
"NumCopies": "1",
"NumPages": "10",
"Status": "done printing",
"Title": "demo.jpg",
"Username": "keshavka",
"date": "23:06 Feb 5, 15",
"print status": "OK",
"time": "1429036296",
"timestamp done printing": "${__time(yyyyMMddHMS)"
}
}
调用print();
函数后收到的输出如下:
""rYajbQx":{[object Object]}"
代码:
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 7; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
//above Code is to generate a Random variable
function test() {
var jobid = Math.random();
var jobkey = jobid;
var time = new Date().getTime()
var kes = makeid()
var joblog = {
"NumCopies": "1",
"Status": "done printing",
"Title": "demo.jpg",
"Username": "keshavka",
"date": "23:06 Feb 5, 15",
"print status": "OK",
"time": "1429036296",
"timestamp done printing": time
};
json = JSON.stringify(joblog);
console.log(joblog);
return joblog;
}
// Above code is to generate JSON
var x = test();
console.log(x);
var y = makeid();
console.log(y);
function print() {
a = ('{' + (test()) + '}');
return a;
}
答案 0 :(得分:0)
好的,我想我知道你想要什么。您希望返回一个具有属性的对象,其中包含您生成的id的名称,并将其值设置为上面代码中列出的属性。我要改变的主要是如何创建对象。因此,在您的测试函数中,我将进行以下更改:
var joblog = {};
joblog[kes] = {
"NumCopies":"1",
"Status": "done printing",
"Title": "demo.jpg",
"Username": "keshavka",
"date": "23:06 Feb 5, 15",
"print status": "OK",
"time": "1429036296",
"timestamp done printing": time
};
因此,如果您生成了&#39; 5YhDv7n&#39;的ID,您将获得一个类型为的对象:
{
5YhDv7n:{
ObjectNumCopies: "1",
Status: "done printing",
Title: "demo.jpg",
Username: "keshavka",
date: "23:06 Feb 5, 15",
print status: "OK",
time: "1429036296",
timestamp done printing: 1435580266234
}
}
我编辑了我JSFiddle以反映这些变化。
答案 1 :(得分:0)
问题是你没有返回JSON,而是返回对象本身。
function test() {
[...]
var json = JSON.stringify(joblog);
console.log(json);
return json;
}