以下代码段从网页中提取数据。
jsonObj = {};
jsonObj.title = this.fetchText('a.profile-full-name');
jsonObj.services = this.getHTML('div.info-list-text span:nth-child(2) span');
jsonObj.services = jsonObj.services.replace(/&/g,"and");
jsonObj.location = this.getHTML('div.pro-info-horizontal-list div.info-list-label:nth-child(3) div.info-list-text span');
jsonObj.contact = this.fetchText('span.pro-contact-text');
jsonObj.description = this.getHTML('div.profile-about div:nth-child(1)');
//jsonObj.description.replace(/\s/g, '');
//require('utils').dump(jsonObj);
jsonObj.description = jsonObj.description.replace(/[\t\n]/g,"");
//jsonObj = JSON.stringify(jsonObj, null, '\t');
require('utils').dump(jsonObj);
它的输出是,
{
"title": "Marcelle Guilbeau, Interior Designer",
"services": "Interior Designers & Decorators",
"location": "5007 Wyoming Ave.",
"description": "Marcelle takes her clients on a journey, drawing out their needs to create an oasis that reflects their personal sense of style and renews their connection."
}
{
"title": "Eric Ross Interiors, LLC",
"services": "Interior Designers & Decorators",
"location": "220 Lewisburg Avenue",
"description": "Eric Ross Interiors exists to create beautiful interiors and a luxury design experience for its clients. We are committed to creating whole room environments for our clients in Nashville, Middle Tennessee and Beyond. Our job is to listen to you about the look and feel you want to achieve. We want to make you comfortable Houzz 2013, 2014, 2015 Outstanding Customer Service and 2015 Best of Design"
}
有没有办法为每个上述对象分配一个键。例如,
"data1": {
"title": "Marcelle Guilbeau, Interior Designer",
"services": "Interior Designers & Decorators",
"location": "5007 Wyoming Ave.",
"description": "Marcelle takes her clients on a journey, drawing out their needs to create an oasis that reflects their personal sense of style and renews their connection."
}
"data2" :{
"title": "Eric Ross Interiors, LLC",
"services": "Interior Designers & Decorators",
"location": "220 Lewisburg Avenue",
"description": "Eric Ross Interiors exists to create beautiful interiors and a luxury design experience for its clients. We are committed to creating whole room environments for our clients in Nashville, Middle Tennessee and Beyond. Our job is to listen to you about the look and feel you want to achieve. We want to make you comfortable Houzz 2013, 2014, 2015 Outstanding Customer Service and 2015 Best of Design"
}
我的最终目标是将这些单个对象转换为json数据。我尝试过使用JSON.stringify
和JSON.parse
但没有运气。
答案 0 :(得分:0)
要使用Javascript创建JSON代码,您应该尝试类似
的内容var someObjectWhichHappensToBeAstring = "user";
var data = {name:someObjectWhichHappensToBeAstring, message:"hello"};
var JSON = JSON.stringify(data);
可以根据需要嵌套。 所以在你的情况下,如果jsonObject已经是一个json对象,你可以简单地这样做:
var data = {data1:jsonObj1, data2:jsonObj2};
var JSON = JSON.stringify(data);