【问题标题】:Convert Json to JS Object with Python使用 Python 将 Json 转换为 JS 对象
【发布时间】:2022-01-12 11:08:21
【问题描述】:

我有一些 excel 文件。我想将它们转换为 JS 对象。我可以像下面这样转换为 Json。

{ "profileMenu.info": "Profile information",
        "profileMenu.infos.generalInfo": "general information",
        "profileMenu.infos.otherInfos": "Other information" }

我需要像这样转换它们。

  profileMenu: {
    info: 'Profile information',
    infos: {
      generalInfo: 'general information',
      otherInfos: 'Other information',
    } 

我已经搜索了执行此操作的方法,但找不到任何方法。您能帮我了解如何将此 Json 转换为 JS 对象吗?

【问题讨论】:

  • { profileMenu.info: "Информация о профиле", 不是有效的 JSON。在 JSON 中,键必须用双引号括起来。除此之外,如果您有 JSON 编码字符串,您可以将其复制并粘贴到 JS 代码中并将其用作 JavaScript 对象。编码为 JSON 的数据是 JS 代码中 JavaScript 对象的有效表示。
  • 嗯,JSON 中的 JSO 代表什么?
  • @t.niese 你说得对,我在 Json 键中有双引号。我编辑了。

标签: javascript python json javascript-objects


【解决方案1】:

如果您愿意使用外部库,

在 javascript 中,您可以使用lodash

var myJSON = {
  "profileMenu.info": "Profile information",
  "profileMenu.infos.generalInfo": "general information",
  "profileMenu.infos.otherInfos": "Other information"
}

let myObject = {}

for (key in myJSON) {
  _.set(myObject, key, myJSON[key]);
}

console.log(myObject)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

在 Python 中,您可以使用 pydash

import pydash

myJSON = {
  "profileMenu.info": "Profile information",
  "profileMenu.infos.generalInfo": "general information",
  "profileMenu.infos.otherInfos": "Other information"
}

myObject = {}

for key in myJSON:
  pydash.set_(myObject, key, myJSON[key])
  
print(myObject)

【讨论】:

    猜你喜欢
    • 2018-08-25
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    相关资源
    最近更新 更多