我有一个结构如下的JSON对象
const inputObj = {
"prop1": "val1",
"prop2": {
"prop2_1": "val2_1",
"prop2_2": "val2_2"
}
"prop3": "val3"
}
我的目标:我想获取属性(包括嵌套属性)并将结果存储在 txt
文件中,但不是 JSON 格式。为了清楚起见,这是我在 txt
文件中的预期输出:
{
prop1: {
id: 'prop1'
},
prop2_prop2_1: {
id: 'prop2.prop2_1'
},
prop2_prop2_2: {
id: 'prop2.prop2_2'
}
prop3: {
id: 'prop3'
}
}
到目前为止,我可以编写非嵌套属性,但仍然不是我期望的结构。这是目前的结果:
{
"prop1": "prop1",
"prop3": "prop3"
}
还是JSON格式,不是我期待的结构,嵌套的属性还是没抓到(还在想怎么抓)
到目前为止,这是生成当前结果的代码:
const fs = require('fs')
const fileName = "./results.txt"
function getAllKeys(obj, path = [], result = []) {
Object.entries(obj).forEach(([k, v]) => {
if (typeof v === 'object') getAllKeys(v, path.concat(k), result)
else result.push(path.concat(k).join("."))
})
return result
}
const inputToFile = getAllKeys(inputObj)
// console.log(inputToFile)
// result of the console.log
// prop1
// prop2.prop2_1
// prop2.prop2_2
// prop3
const newObj = {}
for (var i = 0; i < inputToFile.length; i++) {
var input = inputToFile[i]
var dotIndex = input.indexOf('.') // to check if its from the nested JSON property of the inputObj
if (dotIndex === -1) {
// no dot or nested property in the JSON
newObj[input] = input.toString()
} else {
// if the input contain dot, which is a nested JSON
}
}
fs.writeFileSync(fileName, JSON.stringfy(newObj))
// if I use above line, the result in the file is as I had mention above. But, if the code is like below:
const finals = JSON.stringfy(newObj)
fs.writeFileSync(fileName, JSON.parse(finals))
// the output in the file is only "[Object object]" without double quote
更新 我需要这样格式化结果的原因是因为我想使用 react-intl。我已经有了语言环境文件(翻译),它看起来像 inputObj(结构)。然后,我需要创建一个文件,如下所示,这样 lib 就可以翻译它:
import { defineMessages } from 'react-intl';
const MessagesId = defineMessages({
prop1: {
id: 'prop1'
},
prop2_prop2_1: {
id: 'prop2.prop2_1'
},
prop2_prop2_2: {
id: 'prop2.prop2_2'
},
prop3: {
id: 'prop3'
}
})
export default MessagesId;
这就是为什么,我需要它不像 JSON。因为我已经有了翻译的千码,但是需要在MessagesId中定义。如果我手动操作 .__ 会花费很多时间。 Ps:react-intl 是有效的,问题只是转换为我最初的问题
最佳答案
这个脚本可以处理多层嵌套对象。
const outputObj = {};
const convertNestedObj = (obj, parentKey = []) => {
for (key in obj) {
newParentKey = [...parentKey, key];
if (typeof obj[key] === 'object') {
convertNestedObj(obj[key], newParentKey);
} else {
outputObj[newParentKey.join('_')] = { id: newParentKey.join('_') };
}
}
};
convertNestedObj(inputObj);
关于javascript - 将 JSON 对象转换为非 JSON 格式的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53846100/