用熊猫识别JSON中的标题

时间:2019-02-21 21:21:14

标签: json python-3.x pandas

我有这个JSON文件

*[
  {
    "name": "Kitty",
    "species" : "cat",
    "foods": {
      "likes": ["fresh food"],
      "dislikes": ["stale food"]
    }
  },
  {
    "name": "Pupster",
    "species" : "dog",
    "foods": {
      "likes": ["tomatoes", "peas"],
      "dislikes": ["bread"]
    }
  },
  {
    "name": "Tux",
    "species" : "cat",
    "foods": {
      "likes": ["fancy dishes"],
      "dislikes": ["basic cat food"]
    }
  }
]*

我以这种方式读取该文件:

    content = requests.get("https://raw.githubusercontent.com/LearnWebCode/json-example/master/animals-3.json") 
data = json.loads(content.content)
df = pd.DataFrame(data)

但是我想要的是仅读取JSON文件头并将它们存储在列表中。我有执行类似功能的代码

 getcolumns = list(df.columns.values)

但是我只得到以下内容

  • 名称
  • 种类
  • 食物

我要实现的目标如下:

  • 名称
  • 种类
  • 食物
  • 喜欢
  • 不喜欢

我是新来的熊猫人,任何建议都可以接受

1 个答案:

答案 0 :(得分:0)

列表理解应该起作用:

j = [
  {
    "name": "Kitty",
    "species" : "cat",
    "foods": {
      "likes": ["fresh food"],
      "dislikes": ["stale food"]
    }
  },
  {
    "name": "Pupster",
    "species" : "dog",
    "foods": {
      "likes": ["tomatoes", "peas"],
      "dislikes": ["bread"]
    }
  },
  {
    "name": "Tux",
    "species" : "cat",
    "foods": {
      "likes": ["fancy dishes"],
      "dislikes": ["basic cat food"]
    }
  }
]

getcolumns = [x for x in j[0]] + [x for x in j[0]['foods']]
# ['name', 'species', 'foods', 'likes', 'dislikes']

或者如果您需要数据框:

from pandas.io.json import json_normalize
df = json_normalize(j)

     foods.dislikes       foods.likes     name species
0      [stale food]      [fresh food]    Kitty     cat
1           [bread]  [tomatoes, peas]  Pupster     dog
2  [basic cat food]    [fancy dishes]      Tux     cat