【问题标题】:Reading the json file correctly正确读取 json 文件
【发布时间】:2019-09-04 10:58:13
【问题描述】:

此语句读取 json 文件。但它没有正确拆分列。

df = pd.read_json('https://s3.amazonaws.com/todel162/config1.json', orient='index')

有没有办法使用 pandas 数据框读取 json?

【问题讨论】:

    标签: pandas


    【解决方案1】:

    你可以试试这个。

    import json
    import urllib.request as req
    import pandas as pd
    
    with req.urlopen("https://s3.amazonaws.com/todel162/config1.json") as j:
        raw = json.loads(j.read().decode())
    
    df = pd.DataFrame(raw["configurationItems"])
    df["fileVersion"] = raw["fileVersion"]
    
    print(df)
    

    【讨论】:

      【解决方案2】:

      你可以使用json.json_normalize:

      import json
      from pandas.io.json import json_normalize
      
      with open('config1.json') as f:    
          data = json.load(f)  
      
      df = json_normalize(data, 'configurationItems', ['fileVersion'])
      print (df)
                                                       ARN  awsAccountId  awsRegion  \
      0  arn:aws:cloudtrail:us-east-1:513469704633:trai...  513469704633  us-east-1   
      1  arn:aws:cloudtrail:us-east-1:513469704633:trai...  513469704633  us-east-1   
      
        configurationItemCaptureTime configurationItemStatus  \
      0     2018-07-27T11:52:53.795Z         ResourceDeleted   
      1     2018-07-27T11:52:53.791Z         ResourceDeleted   
      
        configurationItemVersion  configurationStateId configurationStateMd5Hash  \
      0                      1.3         1532692373795                             
      1                      1.3         1532692373791                             
      
        relatedEvents relationships                 resourceId  \
      0            []            []  AWSMacieTrail-DO-NOT-EDIT   
      1            []            []                     test01   
      
                   resourceType supplementaryConfiguration tags fileVersion  
      0  AWS::CloudTrail::Trail                         {}   {}         1.0  
      1  AWS::CloudTrail::Trail                         {}   {}         1.0  
      

      【讨论】:

        猜你喜欢
        • 2021-10-08
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 2023-01-14
        • 2021-01-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多