【问题标题】:How to Parse JSON file and Collect Data and save into a Dataframe?如何解析 JSON 文件并收集数据并保存到数据框中?
【发布时间】:2023-03-26 10:45:01
【问题描述】:

我有一个 JSON 文件,它的格式是:对象数组。每个对象代表一个类。每个 JSON 对象都有一个“methods”键,代表被分析类的所有方法。格式很简单,我们可以在下面的例子中看到 这不是完整的 JSON 文件,它是一个类的块

[
  {
"methods": [
  {
    "parametersTypes": [
      "String"
    ],
    "metricsValues": {
      "ParameterCount": 1.0,
      "CyclomaticComplexity": 1.0,
      "LocalityRatio": 1.0,
      "MethodLinesOfCode": 2.0,
      "MaxCallChain": 1.0
    },
    "fullyQualifiedName": "Smiley.Smiley",
    "smells": []
  },
  {
    "parametersTypes": [
      "String"
    ],
    "metricsValues": {
      "ParameterCount": 1.0,
      "CyclomaticComplexity": 8.0,
      "LocalityRatio": null,
      "MethodLinesOfCode": 23.0,
      "MaxCallChain": 0.0
    },
    "fullyQualifiedName": "Smiley.checkSmiley",
    "smells": [
      {
        "name": "LazyClass",
         "reason": null,
         "startingLine": 3,
         "endingLine": 36
      }
    ]
  }
],
"metricsValues": {
  "PublicFieldCount": 0.0,
  "TightClassCohesion": 0.0,
  "IsAbstract": 0.0,
  "ClassLinesOfCode": 27.0,
  "OverrideRatio": 0.037037037037037035
},
"fullyQualifiedName": "Smiley",
"smells": [
  {
    "name": "LazyClass",
    "reason": null,
    "startingLine": 10,
    "endingLine": 70
  }
]
  }
]

我需要收集 JSON 文件中的所有气味,然后将它们放入 DataFrame 我尝试一堂课 这是我的代码

import json  
from pprint import pprint

with open('Testan.json') as f:
 data = json.load(f)
 pprint(data)

for datum in data[0]["methods"]:
  print(datum['smells'])

这是结果:

 []
 [{'name': 'LazyClass', 'reason': 'null', 'startingLine': 3, 'endingLine': 36}]
 [{'name': 'LazyClass', 'reason': 'null', 'startingLine': 10, 'endingLine': 70}]

首先我需要从这个列表中只需要名称 (LazyClass),然后我需要从所有类 JSON 文件中收集数据,而不是从第一个类中收集数据。

任何帮助,请提前致谢!

【问题讨论】:

    标签: python json dataframe


    【解决方案1】:

    使用下面的代码,您可以将所有类的所有气味添加到your_classes 列表中。所有数据都存储在df 数据框中。您可以通过df['name']访问名称

    your_classes = ['Testan.json','other_names.json']
    your_smells = []
    for filename in your_classes:
        with open(filename) as f:
            data = json.load(f)
    
        for datum in data[0]["methods"]:
            your_smells.append(datum['smells'])
    
    import pandas as pd
    df = pd.DataFrame(your_smells) # Dataframe with all the smells
    print(list(df['name'])) # The list of all names from all classes
    

    【讨论】:

      猜你喜欢
      • 2019-07-02
      • 2013-02-22
      • 1970-01-01
      • 2013-04-19
      • 2018-08-02
      • 1970-01-01
      • 2020-12-26
      • 2017-06-16
      • 1970-01-01
      相关资源
      最近更新 更多