【问题标题】:Is there a way to add curly brackets around a list of dictionaries already existing within a JSON file?有没有办法在 JSON 文件中已经存在的字典列表周围添加大括号?
【发布时间】:2022-06-23 03:17:20
【问题描述】:

我目前有以下格式的 JSON:

[
{
    "ID": "K1",
    "entity": "account_type",
    "values": [
        {
            "type": "synonyms",
            "value": "business",
            "synonyms": [
                "corporate"
            ]
        },
        {
            "type": "synonyms",
            "value": "personal",
            "synonyms": [
                "vanguard",
                "student"
            ]
        }
    ]
},
{
    "ID": "K2",
    "entity": "beverage",
    "values": [
        {
            "type": "synonyms",
            "value": "hot",
            "synonyms": [
                "heated",
                "warm"
            ]
        },
        {
            "type": "synonyms",
            "value": "cold",
            "synonyms": [
                "ice",
                "freezing"
            ]
        }
    ]
}
]

我意识到,对于我的最终产品,我需要的是用花括号括起来并在方括号前包含一个单词。

有没有办法简单地做到这一点?要获取整个列表并将其简单地放入花括号中?

这是我想要的输出格式:

{


"intents": [
    {
      "intent": "password_reset",
      "examples": [
        {
          "text": "abc"
        },
        {
          "text": "def"
        }
      ],
      "description": "ghi"
    }
  ],
  "entities": [
    {
      "entity": "account_type",
      "values": [
        {
          "type": "synonyms",
          "value": "business",
          "synonyms": [
            "company",
            "corporate",
            "enterprise"
          ]
        },
        {
          "type": "synonyms",
          "value": "personal",  
          "synonyms": []
        }
      ],
      "fuzzy_match": true
    }
  ]
}

所以我在原始文件中缺少的基本上是:

{"intents":

和右花括号。尽管稍后我什至会删除它,因为要遵循更多 JSON 代码,但这完全是一个不同的主题,因为从技术上讲 JSON 不会在最后一个花括号之后结束,但我想我不能只附加 " {'intents ':" 到我的 json(?)..

的开头

TIA

【问题讨论】:

  • 如果stuff 是您从输入文件中读取的列表,则json.dumps({"intents": stuff}) 会生成字典。

标签: python json


【解决方案1】:

看来不仅intents key 丢失了,entities 也不见了,所以请阅读内容,将其包裹在丢失的东西中并转储回来

file = 'file.txt'
content = json.load(open(file))

content = {
    "intents": [
        {
            "intent": "password_reset",
            "examples": [
                {
                    "text": "abc"
                },
                {
                    "text": "def"
                }
            ],
            "description": "ghi"
        }
    ],
    "entities": content
}

json.dump(content, open(file, "w"))

【讨论】:

    【解决方案2】:

    如果您将所有 json 作为字符串读取,您可以将“{'intents':”附加到开头并添加结束“}”。

    myJson = "your json string"
    myWrappedJson = "{'intents':" + myJson + "}"
    

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 2019-09-11
      • 2020-12-29
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多