【问题标题】:Count unique values in a JSON计算 JSON 中的唯一值
【发布时间】:2020-06-12 02:38:52
【问题描述】:

我有一个名为 thefile.json 的 json,它看起来像这样:

{
  "domain": "Something",
  "domain": "Thingie",
  "name": "Another",
  "description": "Thing"
}

我正在尝试编写一个 python 脚本,它会在域中生成一组值。在此示例中,它将返回

{'Something', 'Thingie'}

这是我尝试过的:

import json
with open("thefile.json") as my_file: 
  data = json.load(my_file)
  ids = set(item["domain"] for item in data.values())
print(ids)

我收到错误消息

    unique_ids.add(item["domain"])
TypeError: string indices must be integers

查看堆栈交换的答案后,我很难过。为什么我不能将字符串作为索引,因为我正在使用数据类型为字典的 json(我认为!)?如何获取它以便我可以获取“域”的值?

【问题讨论】:

  • 你的item是一个列表,你需要传递一个整数/索引来访问列表中的字符串

标签: python json typeerror


【解决方案1】:

因此,首先,您可以在此处阅读有关 JSON 格式的更多信息:https://www.w3schools.com/python/python_json.asp

其次,字典必须有唯一的键。因此,有两个名为 domain 的键是不正确的。你可以在这里阅读更多关于 python 字典的信息:https://www.w3schools.com/python/python_dictionaries.asp

现在,我推荐以下两种设计,它们应该可以满足您的需求:

  1. 多个名称,多个域:在此设计中,您可以访问网站并检查其每个值的域,例如 ids = set(item["domain"] for item in data["websites"])
{
  "websites": [
    {
      "domain": "Something.com",
      "name": "Something",
      "description": "A thing!"
    },
    {
      "domain": "Thingie.com",
      "name": "Thingie",
      "description": "A thingie!"
    },
  ]
}
  1. 一个名称,多个域:在此设计中,每个网站都有多个域,可以使用JVM_Domains = set(data["domains"]) 访问
{
   "domains": ["Something.com","Thingie.com","Stuff.com"]
   "name": "Me Domains",
   "description": "A list of domains belonging to Me"
}

我希望这会有所帮助。如果我遗漏了任何细节,请告诉我。

【讨论】:

    【解决方案2】:

    您的 JSON 有问题,重复键。我不确定它是否被禁止,但我确定它的格式不正确。 除此之外,当然会给你带来很多问题。

    字典不能有重复键,重复键的返回值是什么?

    所以,修复你的 JSON,像这样,

    {
      "domain": ["Something", "Thingie"],
      "name": "Another",
      "description": "Thing"
    }
    

    你猜怎么着,好的格式几乎可以解决你的问题(你可以在列表中有重复):)

    【讨论】:

    • 这与我推荐的解决方案有何不同?
    • 刚发帖就看到你回答了
    • 哈哈,不用担心。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    相关资源
    最近更新 更多