javascript - 将 JSON 对象转换为非 JSON 格式的对象

标签 javascript json object

我有一个结构如下的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/

相关文章:

javascript - 将整个样式字符串设置为来自 javascript 的元素(不是单个样式参数)

javascript - 如何避免 "Forcing rebuild: JavaScript files need to be re-encrypted"

javascript - 虚拟中继器和 Protractor

javascript - 无法从 HTML 输入元素 ASP.NET 读取 JSON 数据

javascript - 向php发送ajax请求无数据响应

javascript - 如何使用循环获取这些数据?

javascript - 无法弄清楚我做错了什么。未处理的拒绝(类型错误): Cannot read property 'inspection' of undefined

Javascript多维对象覆盖最后插入的项目

javascript - ajax中调用另一个页面的javascript xmlHttp.open

Java 两个不同的文档,完成了一些东西,但现在它们是一个..希望它们分开