在 JavaScript 中将普通字符串转换为对象?

时间:2021-02-04 16:47:01

标签: javascript json

我将此字符串作为输入

"countries" : "[[england, australia], [UAE, China], [UAE]]"

要求

我认为,我需要将此字符串转换为

{"countries": [["england", "australia"], ["UAE", "China"], ["UAE"]]}

然后我可以使用 json.parse() 方法在 js 中将 它转换为 Object

我尝试了各种方法,但似乎都不起作用。

我试过了

  1. JSON.stringify
  2. JSON.parse
  3. 评估

我已经在 J​​ava 中完成了这项工作,但在 Javascript 中无法这样做。 我是 js 新手,因为在 java 中我可以轻松地执行此 JSONObject。

任何帮助将不胜感激,谢谢!!

1 个答案:

答案 0 :(得分:0)

这需要多个步骤:

将输入用花括号括起来并执行 JSON.parse

const input = "\"countries\" : \"[[england, australia], [UAE, China], [UAE]]\""
const result = JSON.parse("{" + input + "}")

这会给你一个对象:

{
    "countries": "[[england, australia], [UAE, China], [UAE]]"
}

然后用双引号将内部字符串包裹起来,再次解析:

const inner = result.countries
result.countries = JSON.parse(inner.replaceAll(/([a-zA-Z]+)/g, '"$1"'))

这给你result

{
  "countries": [
    [
      "england",
      "australia"
    ],
    [
      "UAE",
      "China"
    ],
    [
      "UAE"
    ]
  ]
}
相关问题