代码之家  ›  专栏  ›  技术社区  ›  Oalvinegro

从包含json到excel的api链接导入数据[已关闭]

  •  -3
  • Oalvinegro  · 技术社区  · 7 年前

    我想从这个链接导入数据 https://api.cartolafc.globo.com/time/slug/umo/16 (最后两个引用,“umo”和“16”是动态的)到spreedsheet,将引用链接到单元格。 我对API或JSON一无所知。有“简单”的方法吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   omegastripes    7 年前

    首先,您需要检查JSON响应的结构,使用任何联机JSON查看器(例如 http://jsonviewer.stack.hu/ ),其中您可以看到您的JSON对象包含 atletas. array, clubes. , posicoes. , status. ,。<代码>时间 对象,以及具有标量值的几个属性:

    此外,在 atletas array中还有对象,每个对象都包含一些可以在工作表中填充的属性:

    下面是显示如何检索这些值的VBA示例。 import json.bas module into the vba project for json processing.

    子测试()
    
    将sjsonstring变为字符串
    迪默森
    将sstate变暗为字符串
    DATA ADATA()
    幽暗地域
    模糊结果
    暗号
    
    '检索JSON内容
    使用CreateObject(“msxml2.xmlhttp”)。
    .open“get”,“https://api.cartolafc.globo.com/time/slug/umo/16”,true
    发送
    do until.readystate=4:doEvents:循环
    sjsonString=.ResponseText
    以结束
    '分析JSON示例
    json.parse sjsonstring、vjson、sstate
    如果sstate=“错误”,则
    msgbox“无效的json”
    终点
    结束如果
    '处理单个属性的示例
    对象的“get”atletas数组,没有数组的set关键字
    Vresult=Vjson(“Atletas”)。
    “”可选获取对象的“clubes”对象,设置用于字典表示的对象的关键字
    ''设置vresult=vjson(“clubes”)
    '转换为二维数组
    Json.Toarray Vresult、Adata、Aheader
    '将二维数组输出到第一个工作表
    使用此工作簿。工作表(1)
    删除
    .cells.wraptex=错误
    输出数组。单元格(1,1),标题
    输出2darray.cells(2,1),adata
    .列.自动调整
    以结束
    从根对象中移除“atletas”数组
    移除“atletas”
    '删除除第一个工作表以外的所有工作表
    application.displayAlerts=false
    使用此工作簿。工作表
    do until.count=1
    .item(.count).delete
    回路
    以结束
    application.displayAlerts=真
    '在单独的工作表上处理乘法属性的示例
    '处理所有其他对象和数组
    对于vjson中的每个sname
    '检查属性是数组还是对象
    如果isarray(vjson(sname))或isobject(vjson(sname)),则
    '转换为二维数组
    json.toarray vjson(sname)、adata、aheader
    '将二维数组输出到工作表
    使用thisworkbook.sheets.add“创建新的输出工作表”
    输出数组。单元格(1,1),标题
    输出2darray.cells(2,1),adata
    .列.自动调整
    以结束
    '从根对象删除输出对象
    vjson.删除sname
    结束如果
    接下来
    '使用保留在根对象中的标量值处理所有其余属性
    '将根对象转换为二维数组
    json.toarray vjson、adata、aheader
    '将二维数组输出到工作表
    使用thisworkbook.sheets.add“创建新的输出工作表”
    输出数组。单元格(1,1),标题
    输出2darray.cells(2,1),adata
    .列.自动调整
    以结束
    '或者整个JSON结构可以扁平化并输出到工作表
    '分析JSON示例
    json.parse sjsonstring、vjson、sstate
    压扁杰森
    平面VJSON,Vresult
    '将扁平的JSON转换为二维数组
    Json.Toarray Vresult、Adata、Aheader
    '将二维数组输出到工作表
    使用thisworkbook.sheets.add“创建新的输出工作表”
    输出数组。单元格(1,1),标题
    输出2darray.cells(2,1),adata
    .列.自动调整
    以结束
    msgbox“已完成”
    
    结束子
    
    子输出数组(odstrng为range,acells为variant)
    
    与奥德斯特朗
    家长选择
    具有.resize(1,ubound(acells)-lbound(acells)+1)
    .numberFormat=“@”
    值=ACELLS
    以结束
    以结束
    
    结束子
    
    子输出2数组(odstrng为range,acells为variant)
    
    与奥德斯特朗
    家长选择
    调整大小()
    UBound(Acells,1)-LBound(Acells,1)+1,,_
    UBound(Acells,2)-LBound(Acells,2)+1)
    .numberFormat=“@”
    值=ACELLS
    以结束
    以结束
    
    结束子
    < /代码> 
    
    

    atletasarray for me的输出如下:

    顺便说一句,在以下答案中应用的类似方法:1,2,3,4,5,6,7,5“>5 5>>,,6,,,11.,12.,13.,14.,15.,16,17,18,19and20

    ,您可以看到JSON对象包含atletas数组,clubes,posicoes,status,time对象和具有标量值的几个属性:

    JSON

    再往前走,里面有物体阿特莱斯数组,每个数组都包含一些可以在工作表上填充的属性:

    atletas array

    下面是显示如何检索这些值的VBA示例。进口JSON.bas模块进入vba项目进行json处理。

    Option Explicit
    
    Sub Test()
    
        Dim sJSONString As String
        Dim vJSON
        Dim sState As String
        Dim aData()
        Dim aHeader()
        Dim vResult
        Dim sName
    
        ' Retrieve JSON content
        With CreateObject("MSXML2.XMLHTTP")
            .Open "GET", "https://api.cartolafc.globo.com/time/slug/umo/16", True
            .send
            Do Until .readyState = 4: DoEvents: Loop
            sJSONString = .responseText
        End With
        ' Parse JSON sample
        JSON.Parse sJSONString, vJSON, sState
        If sState = "Error" Then
            MsgBox "Invalid JSON"
            End
        End If
        ' Example of processing single property
        ' Get 'atletas' array of objects, there is no Set keyword for arrays
        vResult = vJSON("atletas")
        '' Optional get 'clubes' object of objects, Set keyword used for objects represented by dictionaries
        '' Set vResult = vJSON("clubes")
        ' Convert to 2d array
        JSON.ToArray vResult, aData, aHeader
        ' Output 2d array to first worksheet
        With ThisWorkbook.Sheets(1)
            .Cells.Delete
            .Cells.WrapText = False
            OutputArray .Cells(1, 1), aHeader
            Output2DArray .Cells(2, 1), aData
            .Columns.AutoFit
        End With
        ' Remove 'atletas' array from root object
        vJSON.Remove "atletas"
        ' Remove all worksheets but the first
        Application.DisplayAlerts = False
        With ThisWorkbook.Sheets
            Do Until .Count = 1
                .Item(.Count).Delete
            Loop
        End With
        Application.DisplayAlerts = True
        ' Example of processing multiply properties on separate worksheets
        ' Processing all the rest of objects and arrays
        For Each sName In vJSON
            ' Check if the property is array or object
            If IsArray(vJSON(sName)) Or IsObject(vJSON(sName)) Then
                ' Convert to 2d array
                JSON.ToArray vJSON(sName), aData, aHeader
                ' Output 2d array to worksheet
                With ThisWorkbook.Sheets.Add ' Create new worksheet for output
                    OutputArray .Cells(1, 1), aHeader
                    Output2DArray .Cells(2, 1), aData
                    .Columns.AutoFit
                End With
                ' Remove output object from root object
                vJSON.Remove sName
            End If
        Next
        ' Processing all the rest of properties with scalar values which remain in root object
        ' Convert root object to 2d array
        JSON.ToArray vJSON, aData, aHeader
        ' Output 2d array to worksheet
        With ThisWorkbook.Sheets.Add ' Create new worksheet for output
            OutputArray .Cells(1, 1), aHeader
            Output2DArray .Cells(2, 1), aData
            .Columns.AutoFit
        End With
        ' Or the whole JSON structure could be flattened and output to worksheet
        ' Parse JSON sample
        JSON.Parse sJSONString, vJSON, sState
        ' Flatten JSON
        JSON.Flatten vJSON, vResult
        ' Convert flattened JSON to 2d array
        JSON.ToArray vResult, aData, aHeader
        ' Output 2d array to worksheet
        With ThisWorkbook.Sheets.Add ' Create new worksheet for output
            OutputArray .Cells(1, 1), aHeader
            Output2DArray .Cells(2, 1), aData
            .Columns.AutoFit
        End With
        MsgBox "Completed"
    
    End Sub
    
    Sub OutputArray(oDstRng As Range, aCells As Variant)
    
        With oDstRng
            .Parent.Select
            With .Resize(1, UBound(aCells) - LBound(aCells) + 1)
                .NumberFormat = "@"
                .Value = aCells
            End With
        End With
    
    End Sub
    
    Sub Output2DArray(oDstRng As Range, aCells As Variant)
    
        With oDstRng
            .Parent.Select
            With .Resize( _
                    UBound(aCells, 1) - LBound(aCells, 1) + 1, _
                    UBound(aCells, 2) - LBound(aCells, 2) + 1)
                .NumberFormat = "@"
                .Value = aCells
            End With
        End With
    
    End Sub
    

    输出为阿特莱斯我的数组如下:

    enter image description here

    顺便说一句,类似的方法适用于以下答案:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,1920.

    推荐文章