在 json 中加入多个 json 文件,并将其路径作为键
Posted
技术标签:
【中文标题】在 json 中加入多个 json 文件,并将其路径作为键【英文标题】:join multible json files in on json with its path as a key 【发布时间】:2021-12-01 17:50:10 【问题描述】:我有一些 json 文件,我想将它们加入一个 json 文件,但我需要将每个人都设置在其路径的键下,这样,当我使用大 json 文件时,我可以很容易地得到它们
const jsonFullPath = path.relative(root, file).split(path.sep).join('.')
.replace(/(_[a-z]2(_[A-Z]2)?)?\.json/, '') + '.' ;
const obj = [jsonFullPath];
let rawdata = fs.readFileSync(file);
let student = JSON.parse(rawdata);
上面的代码在一个 json 文件数组中调用
请大家帮忙
一个例子是这样的:
"sessionTimer":
"accessibleTimingOut": "timeoutMinutes minutes until this
page times out. Move your mouse pointer or press any key to
extend the time with extendMinutes minutes.",
"reload": "Reload",
"timedOut": "The page has timed out and needs to be reloaded.",
"timingOut": "seconds until this page times out and needs to be
reloaded. Move your mouse pointer or press any key to extend the
time with extendMinutes minutes."
,
"header":
"screenReaderLabel": "Poslechnout",
"myAccountLabel": "Přihlásit se",
"myAccountLogoutLabel": "Odhlásit se",
"myAccountPagesLabel": "Moje stránky",
"newToTheLibrary": "Jste v knihovně noví?",
"joinTheLibraryLabel": "Registrovat do knihovny",
"openingsLabel": "Provozní doba",
"languageLabel": "Jazyk"
,
"branchOpeningHours":
"headerLabel": "Provozní doba",
"closedLabel": "Zavřeno",
"todayLabel": "Dnes",
"navigationBackLabel": "Zpět",
"navigationNextLabel": "Další",
"navigationPreviousLabel": "Předchozí",
"serviceTypeClosedLabel": "Zavřeno",
"serviceTypeStaffedLabel": "S personálem",
"serviceTypeSelfServiceLabel": "Samoobsluha",
"typeRegularLabel": "Pravidelný",
"typeSpecialLabel": "Zvláštní",
"viewAllLabel": "Zobrazit veškerou otevírací dobu"
加入后会有一些这样的想法;
"modules.provider.assets.locales.en_US.translation":
"sessionTimer":
"accessibleTimingOut": "timeoutMinutes minutes until this
page times out. Move your mouse pointer or press any key to
extend the time with extendMinutes minutes.",
"reload": "Reload",
"timedOut": "The page has timed out and needs to be reloaded.",
"timingOut": "seconds until this page times out and needs to be
reloaded. Move your mouse pointer or press any key to extend the
time with extendMinutes minutes."
,
"header":
"screenReaderLabel": "Poslechnout",
"myAccountLabel": "Přihlásit se",
"myAccountLogoutLabel": "Odhlásit se",
"myAccountPagesLabel": "Moje stránky",
"newToTheLibrary": "Jste v knihovně noví?",
"joinTheLibraryLabel": "Registrovat do knihovny",
"openingsLabel": "Provozní doba",
"languageLabel": "Jazyk"
,
"branchOpeningHours":
"headerLabel": "Provozní doba",
"closedLabel": "Zavřeno",
"todayLabel": "Dnes",
"navigationBackLabel": "Zpět",
"navigationNextLabel": "Další",
"navigationPreviousLabel": "Předchozí",
"serviceTypeClosedLabel": "Zavřeno",
"serviceTypeStaffedLabel": "S personálem",
"serviceTypeSelfServiceLabel": "Samoobsluha",
"typeRegularLabel": "Pravidelný",
"typeSpecialLabel": "Zvláštní",
"viewAllLabel": "Zobrazit veškerou otevírací dobu"
【问题讨论】:
那么你希望你的对象有一个嵌套结构(即表示目录结构)还是只是扁平的,即所有元素都是顶层,它们的完整路径作为键? 感谢您的回答,我想要它作为嵌套结构 您的示例不是嵌套结构,因为所有元素都将位于文件的顶层。嵌套结构类似于 "modules": "provider": "assets": ...
而不是 "modules.provider.assets": ...
obs,我以为是嵌套结构但是没问题你现在知道我愿意有什么,请你给我一个解决方案
【参考方案1】:
假设您有一个 files
列表要添加到您的 JSON 中,并且您的 jsonFullPath
已正确创建,那么以下应该可以工作
let files = [...]; //your json files you want to add
let myobj = files.reduce((obj, file) =>
//not sure why you are appending an addtional "." at the end ...
let key = path.relative(root, file).split(path.sep).join('.')
.replace(/(_[a-z]2(_[A-Z]2)?)?\.json/, '') + '.' ;
obj[key] = JSON.parse(fs.readFileSync(file, "utf-8"));
return obj;
, as [key: string]: any);
即对files
数组中的每个文件执行Array.reduce
的回调。它将文件名转换为您想要的键,然后从磁盘读取文件(取决于此代码运行的位置,您可能应该使用 fs.readFile()
的异步变体,因为 readFileSync
会阻止您的执行)并添加解析的对象到你的结果对象
如果你更喜欢循环,你也可以这样做
let files = [...];
let myobj : [key: string]: any = ;
files.forEach(file =>
let key = path.relative(root, file).split(path.sep).join('.')
.replace(/(_[a-z]2(_[A-Z]2)?)?\.json/, '') + '.' ;
myobj[key] = JSON.parse(fs.readFileSync(file, "utf-8"));
);
或使用简单的for .. of
循环
let files = [...];
let myobj : [key: string]: any = ;
for (let file of files)
let key = path.relative(root, file).split(path.sep).join('.')
.replace(/(_[a-z]2(_[A-Z]2)?)?\.json/, '') + '.' ;
myobj[key] = JSON.parse(fs.readFileSync(file, "utf-8"));
【讨论】:
我在尝试你的方法时遇到了一个错误:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“”。在类型“ 上找不到具有类型参数“字符串”的索引签名 抱歉,错过了您问题上的typescript
标签。请通过正确的输入查看更新的答案【参考方案2】:
你的意思是这样的?
let myJson = '';
myJson += `$jsonFullPath: $rawdata`;
myJson += '';
你可以构建你的最终字符串。
【讨论】:
不,那不行 为什么不起作用? 因为它没有创建对象,而且该代码创建的字符串不是有效的JSON,因此无法解析为对象... 我刚刚写好了,但它背后的想法绝对应该有效 my.full.path.1: original: data
。你也这样做,只是直接使用对象。我对这个问题本身更感到惊讶,因为除了大的 json 膨胀之外,它还询问如何向它添加自定义键和值,所以我只是指出了那个方向。但是,是的,您的完整正确版本要好得多:)。
@Gonzi 你试过你的代码了吗?它将产生完全(即没有任何替换)以下字符串 "jsonFullPath:rawdata"
。如果你循环它,结果将是"jsonFullPath:rawdatajsonFullPath:rawdata"
那么这对显然是初学者的开发人员有何帮助?【参考方案3】:
我找到了解决方案:
假设你处于循环、映射或归约...
所以每次你传递一个文件(在我们的例子中是一个 JSON)
const file = "sessionTimer":
"accessibleTimingOut": "timeoutMinutes minutes
until this page times out. Move your mouse pointer
or press any key to extend the time with
extendMinutes minutes.",
"reload": "Reload",
"timedOut": "The page has timed out and needs to
be reloaded.",
"timingOut": "seconds until this page times out
and needs to be
reloaded. Move your mouse pointer or press any
key to extend the time with extendMinutes
minutes." ,
;
var key = "filePath";
var json = [key]:fs.readFileSync(file,"utf-8");
console.log(json);
控制台会给出:
"filePath": "sessionTimer":
"accessibleTimingOut": "timeoutMinutes minutes
until this page times out. Move your mouse pointer
or press any key to extend the time with
extendMinutes minutes.",
"reload": "Reload",
"timedOut": "The page has timed out and needs to
be reloaded.",
"timingOut": "seconds until this page times out
and needs to be
reloaded. Move your mouse pointer or press any
key to extend the time with extendMinutes
minutes." ,
;
【讨论】:
你确定这有效吗?因为readFileSync
不指定文件编码会返回一个Buffer
。即使您指定了编码,您也可以将文件内容添加为字符串 ...
我同意你的观点,我会用它来编码谢谢,如果你可以的话,我还有另一个问题,可以提供帮助***.com/questions/69566955/…你看起来非常熟练的开发人员,我是 nodejs 和 javascript 的初学者世界
您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。以上是关于在 json 中加入多个 json 文件,并将其路径作为键的主要内容,如果未能解决你的问题,请参考以下文章
json - 如何在 flutter 中的List String中加入2 json值?