【发布时间】:2018-10-19 06:52:37
【问题描述】:
我在网上搜索了很多解析json数组的文章,或者有任何npm包可以做到这一点。但是我所有的努力都白费了。
我有一个这样的 json 数组 =>
{
"pctProjects": [
{
"ID": "1",
"Name": "Software Upgrade",
"Desc": "GO! V1 Chapter 5- EOC Mastery Exercise",
"AppId": "1",
"UserId": "1",
"CreatedDate": "2008-07-30T00:00:00",
"Score": "100",
"SeriesID": "2",
"IsPublished": "1",
"PublishedLMSVariationID": "5",
"IsPCTActive": "0",
"IVTEnabled": "0",
"IsActiveInSelectPopup": "1",
"Chapter": "CH05"
},
{
"ID": "2",
"Name": "Business Venture",
"Desc": "Exploring Volume 1 Chapter 3- TST Exercise",
"AppId": "1",
"UserId": "1",
"CreatedDate": "2008-07-30T00:00:00",
"Score": "100",
"SeriesID": "1",
"IsPublished": "1",
"PublishedLMSVariationID": "7",
"IsPCTActive": "0",
"IVTEnabled": "0",
"IsActiveInSelectPopup": "1",
"Chapter": "CH03"
}
.
.
.
我使用 Json.parse 方法遍历了我的 json 数组“pctProjects”,并且能够使用我需要用另一个值替换的属性 PublishedLMSVariationID 找到对象,我正在使用文件系统模块函数,如 appendFileSync() 和 writeFileSync( (
而且使用文件中的替换也不能帮助我实现目标。
还添加我的代码 sn-p 我现在正在做的事情,但没有优化。
for(let item of gulpJson.pctProjects){
// console.log(typeof touseVariationId)
if(counter==1 && item.PublishedLMSVariationID == results[0]){
item.PublishedLMSVariationID = results[1]
fs.writeFileSync(path.join(dir,'PCT5_MasterPCTProjectsForGulp.json'), JSON.stringify(item,null,4));
counter++;
}
else if(counter==1 && item.PublishedLMSVariationID != results[0]){
fs.writeFileSync(path.join(dir,'PCT5_MasterPCTProjectsForGulp.json'), JSON.stringify(item,null,4));
counter++;
}
else if(item.PublishedLMSVariationID == results[0]){
item.PublishedLMSVariationID = results[1]
fs.appendFileSync(path.join(dir,'PCT5_MasterPCTProjectsForGulp.json'), JSON.stringify(item,null, 4));
// break
// fs.writeFileSync(path.join(dir,'PCT5_MasterPCTProjectsForGulp.json',null, 2), JSON.stringify(item));
}
else
fs.appendFileSync(path.join(dir,'PCT5_MasterPCTProjectsForGulp.json'),","+"\n"+"\t"+ JSON.stringify(item,null, 4));
}
问题:
- 有什么办法可以只替换nodejs中json数组中的一个json属性???
非常感谢:)。提前致谢。
如果需要更多信息,请发表评论。
【问题讨论】:
-
如何在 json 数组中替换我的 json 对象的一个属性,它在 nodejs 中没有大量 json 对象 真的不清楚你要什么。我看到的只是一组具有相同数量属性的对象
-
如果您要问如何以某种方式解析文件而不先将其加载到 RAM 中,恐怕这不是计算机的工作方式。如果不加载整个文件、对其进行更改,然后将其写回 HD,您将无法实现。
-
@GeorgeBailey,我只需要替换一个 json 对象的一个属性,所以我只想替换文件中的那个属性,而不是重写文件中的所有内容。
-
当然,读取整个文件,更新值,然后写入整个文件比打开、写入和关闭文件数百甚至数千次所花费的时间要少得多......?
-
@ChrisG,你为什么要告诉我这个,我知道这个。我要求这样做。
标签: javascript arrays json node.js