【问题标题】:Extracting a value from json and using as a key in new dictionary从 json 中提取值并用作新字典中的键
【发布时间】:2023-01-12 08:02:10
【问题描述】:

我有一个 Json 文件,想从中提取一些信息到一个新的字典中。

json 看起来像这样:

{
    "code": "C568219u",
    },
    "body_text": [
        {
            "text": "some text",
            "other_item": "3fd"
            }
            {
            "text": "more text"
            }
            ]
}

我想获取“代码”——这是问题所在——作为我的新字典中的键,并将文本作为值。

理想情况下,字典看起来像这样:

{C568219u:"all the text"}

为了提取文本,它的工作方式如下:

with open("C:\\root\test.json", 'r') as content:
            try:
                temp = []
                json_file = json.load(content)
                for item in json_file["body_text"]:
                    temp.append(item["text"]) 
                    text = " ".join(f)
            except:
                print(":(")
  

print(text)

但是现在提取“代码”并将其设置为键,然后更新字典对我的代码不起作用。

到目前为止看起来像这样:

full_text= {}
with open("C:\\root\test.json", 'r') as content:
            try:
                json_file = json.load(content)
                temp = []
                if 'code' in content:
                    c_id = content['code']    
               
                    for item in json_file["body_text"]:
                        temp.append(item["text"])   
                        text = " ".join(temp)
                        full.update[c_id:text]
                    
            except:
                print(":(")


关于问题可能是什么以及如何实现我的目标的任何想法?

【问题讨论】:

  • if 'code' in content: 大概你是想说 if 'code' in json_file: 吧。
  • 还有,那是一个糟糕的处理异常的方式。您故意隐藏了实际的错误,这意味着您将完全不知道到底出了什么问题。
  • @JohnGordon 它尝试更改它,但没有什么不同。至于异常,它在没有 try/except 的情况下运行代码并且没有抛出错误,但也没有工作。
  • 你的例子太过努力地帮助我们,反而让事情变得更糟。什么是“全文”?不要告诉我们获取所有文本,而是准确地告诉我们该示例的所有文本应该是什么。应该是“一些文字更多文字”吗?
  • 在我修复所有 json 错误和明显的 python 错误之后,这似乎工作正常。我建议您只调试代码。不要抑制异常——让它们停止你的程序并告诉你要修复什么。然后修复它。

标签: python json dictionary


【解决方案1】:

不确定这是否是理想的方式,但我将代码更改为:

full_text= {}
with open("C:\root	est.json", 'r') as content:
            try:
                json_file = json.load(content)
                temp = []
                for item in json_file:
                    c_id = content['code']    
               
                    for item in json_file["body_text"]:
                        temp.append(item["text"])   
                        text = " ".join(temp)
                        almost = {c_id:text}
                        full.update(almost)
                    
            except:
                print(":(")

它奏效了。

仍然不太了解 json 文件,但这样它就按照我想要的方式出现了! 是的!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 2019-10-04
    • 2018-01-31
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多