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

问题描述 投票:2回答:1

我有一个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。我已经有了locale文件(翻译),它看起来像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是有效的,问题只是转换为我的初始问题

javascript json object
1个回答
0
投票

此脚本可以处理多个级别的嵌套对象。

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);
© www.soinside.com 2019 - 2024. All rights reserved.