Как я могу использовать Power запрос, чтобы превратить ответ API json в таблицу? - PullRequest
0 голосов
/ 01 февраля 2020

, так как из-за ключа api у меня возникают проблемы, мне приходится загружать json данные в формате, используя vba, а не запрос мощности. ответ API, я хотел бы проанализировать в таблице или использовать Power запрос, чтобы превратить в таблицу.

Код, который я пробовал, не работает. это дает мне .... Ошибка времени выполнения 10001 "Ожидается" "" или "» .... Я уверен, что это как-то связано с кодом "JSONConverter", который я скачал и попытался использовать. Это веб-сайт это помогло мне разобраться в коде, который я написал http://excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/. Я открыт для удаления, если у кого-то есть лучший способ сделать это. и, наконец, это достаточно большой объем данных для помещения в одну ячейку. Вы рекомендуете использовать ячейку или какой-либо другой способ хранения данных, которые будут проанализированы?

это образец файла json


Dim jsonText As String
Dim jsonObject As Object, item As Object
Dim i As Long
Dim ws As Worksheet

Set ws = Worksheets("sheet20")

'ws.Cells(1, 1).Value = res
jsonText = ws.Cells(1, 1)

Set jsonObject = JsonConverter.ParseJson(jsonText)

i = 3

ws.Cells(2, 1) = "WorkOrderNumber"
'ws.Cells(2, 2) = "Customer Name"
'ws.Cells(2, 3) = "Location Name"
'ws.Cells(2, 4) = "IsInvoiced"
'ws.Cells(2, 5) = "Team"
'ws.Cells(2, 6) = "WorkOrderDate"
'ws.Cells(2, 7) = "DateFinished"
'ws.Cells(2, 8) = "ScheduledTime"
'ws.Cells(2, 9) = "EstimatedDuration"
'ws.Cells(2, 10) = "Notes"
'ws.Cells(2, 11) = "PrivateNotes"
'ws.Cells(2, 1) = "SalesRepresentative"
'ws.Cells(2, 2) = "Description"
'ws.Cells(2, 3) = "Status"
'ws.Cells(2, 4) = "IsInvoiced"
'ws.Cells(2, 5) = "Team"
'ws.Cells(2, 6) = "WorkOrderDate"
'ws.Cells(2, 7) = "DateFinished"
'ws.Cells(2, 8) = "ScheduledTime"
'ws.Cells(2, 9) = "EstimatedDuration"
'ws.Cells(2, 10) = "Notes"
'ws.Cells(2, 11) = "PrivateNotes"
'ws.Cells(2, 12) = "CreatedBy"
'ws.Cells(2, 13) = "CreatedOn"
'ws.Cells(2, 14) = "UpdatedOn"
'ws.Cells(2, 15) = "UpdatedBy"
'ws.Cells(2, 16) = "Version"

For Each item In jsonObject("Data")
    ws.Cells(i, 1) = item("WorkOrderNumber")
    'ws.Cells(i, 2) = item("Customer")("Name")
    'ws.Cells(i, 3) = item("Location")("Name")
    'ws.Cells(i, 4) = item("Location")("Name")
    'ws.Cells(i, 5) = item("Location")("Name")
    'ws.Cells(i, 6) = item("WorkOrderDate")
    'ws.Cells(i, 7) = item("DateFinished")
    'ws.Cells(i, 8) = item("ScheduledTime")
    'ws.Cells(i, 9) = item("EstimatedDuration")
    'ws.Cells(i, 10) = item("Notes")
    'ws.Cells(i, 11) = item("PrivateNotes")
    'ws.Cells(i, 1) = item("SalesRepresentative")("Name")
    'ws.Cells(i, 2) = item("Description")
    'ws.Cells(i, 3) = item("Status")
    'ws.Cells(i, 4) = item("IsInvoiced")
    'ws.Cells(i, 5) = item("Team")("Name")
    'ws.Cells(i, 6) = item("WorkOrderDate")
    'ws.Cells(i, 7) = item("DateFinished")
    'ws.Cells(i, 8) = item("ScheduledTime")
    'ws.Cells(i, 9) = item("EstimatedDuration")
    'ws.Cells(i, 10) = item("Notes")
    'ws.Cells(i, 11) = item("PrivateNotes")
    'ws.Cells(i, 12) = item("Metadata")("CreatedBy")
    'ws.Cells(i, 13) = item("Metadata")("CreatedOn")
    'ws.Cells(i, 14) = item("Metadata")("UpdatedOn")
    'ws.Cells(i, 15) = item("Metadata")("UpdatedBy")
    'ws.Cells(i, 16) = item("Metadata")("Version")

Next

    End Sub

'here is an example of the json file i want to turn into 1 table
{
  "TotalCount": 148,
  "Data": [
    {
      "WorkOrderNumber": "PV 298-0-0",
      "Scheduler": {
        "SchedulerId": 19469471,
        "SchedulerNumber": "PV 298-0-0",
        "ScheduleType": "Project"
      },
      "Customer": {
        "Inactive": false,
        "Id": 6985214,
        "Name": "blah"
      },
      "Location": {
        "Id": 7513954,
        "Name": "Primary"
      },
      "GeoCoordinates": null,
      "CoordinatesCaptured": null,
      "Contact": {
        "Id": 7316098,
        "Name": "blah"
      },
      "ThirdPartyBillPayer": null,
      "IsMarketingCampaignSetByLead": false,
      "MarketingCampaign": {
        "Id": 115753,
        "Name": "Web Call In"
      },
      "JobCategory": null,
      "SalesRepresentative": {
        "Id": 242299,
        "Name": "blah"
      },
      "DefaultEquipment": null,
      "Description": "Gutter/Guard Estimate",
      "Status": "Suspended",
      "IsInvoiced": false,
      "Branch": {
        "Id": 145945,
        "Name": "-VA"
      },
      "Team": {
        "Id": 177760,
        "Name": "blah"
      },
      "TeamMembers": [
        {
          "EmployeeId": 242299,
          "UserId": 179578,
          "FirstName": "blah",
          "LastName": "Bblah",
          "Email": "blah.com",
          "Title": null
        }
      ],
      "ConfirmationStatus": "SentEmail",
      "WorkOrderDate": "2017-05-24T00:00:00",
      "DateFinished": null,
      "ScheduledTime": 1097,
      "EstimatedDuration": 25,
      "ArrivalWindow": 60,
      "EarliestArrival": null,
      "LatestDeparture": null,
      "Notes": "Client requests new seamless 5\" white gutters and downspouts to prevent sol erosion around foundation of home. Client has also requested we install One Guard with 20yr money back guarantee. Due to client replacing siding,we've agreed to remove existing gutters and come back to install new gutters on a separate day as close to the siding job beginning and ending as possible.",
      "PrivateNotes": "blah",
      "InvoiceNotes": null,
      "ReminderType": "None",
      "ReminderValue": 0,
      "ReminderMessage": "",
      "WorkOrderLines": [],
      "CustomFields": [
        {
          "Name": "CC Referred By",
          "Value": ""
        },
        {
          "Name": "E3 Electric:",
          "Value": ""
        },
        {
          "Name": "W3 Yard Sign Posted",
          "Value": ""
        },
        {
          "Name": "P2 Materials Checked",
          "Value": ""
        },
        {
          "Name": "P3 Photos & Diagrams Included",
          "Value": ""
        },
        {
          "Name": "W8 Referrals given to Customer",
          "Value": ""
        },
        {
          "Name": "E2 Ladders Needed:",
          "Value": ""
        },
        {
          "Name": "P4 Priority List",
          "Value": "False"
        },
        {
          "Name": "P Material Box",
          "Value": ""
        },
        {
          "Name": "E4 Takedown",
          "Value": ""
        },
        {
          "Name": "W6 Describe Delays",
          "Value": ""
        },
        {
          "Name": "W7 Final walk around/Payment Taken",
          "Value": ""
        },
        {
          "Name": "W5 Amount of  Delay Due To Work Obstacles",
          "Value": ""
        },
        {
          "Name": "W Tools/Materials visually inspected",
          "Value": ""
        },
        {
          "Name": "E Roof Pitch",
          "Value": ""
        },
        {
          "Name": "E1 Roof Material ",
          "Value": ""
        },
        {
          "Name": "CC1 Marketing Source Correction",
          "Value": ""
        },
        {
          "Name": "CC4 Estimate Summary Correction",
          "Value": ""
        },
        {
          "Name": "S Walk Around Done",
          "Value": ""
        },
        {
          "Name": "S1 All Expectations Set In Writing/Photos",
          "Value": ""
        },
        {
          "Name": "S2 I Feel Est. Will Close In",
          "Value": ""
        },
        {
          "Name": "S3 I went for",
          "Value": ""
        },
        {
          "Name": "E5 Movement Difficulty",
          "Value": ""
        },
        {
          "Name": "CC3 Time Lost ",
          "Value": ""
        },
        {
          "Name": "S4 Est Rating",
          "Value": ""
        },
        {
          "Name": "S6 Reason Client Chose our Company",
          "Value": ""
        },
        {
          "Name": "S5 Solutionist notes",
          "Value": ""
        },
        {
          "Name": "W1 Called in Rought",
          "Value": ""
        },
        {
          "Name": "W2 initial walk around completed",
          "Value": ""
        },
        {
          "Name": "W4 Safety Concerns/Description",
          "Value": ""
        },
        {
          "Name": "W9 Client Rating",
          "Value": ""
        },
        {
          "Name": "S7 Follow Up Notes",
          "Value": ""
        },
        {
          "Name": "CC5 Reasons for Area of Improvement",
          "Value": ""
        },
        {
          "Name": "CC2 Est. Scheduling Area of Improvement",
          "Value": ""
        },
        {
          "Name": "P1 Man Hours",
          "Value": ""
        }
      ],
      "Id": 19469471,
      "Metadata": {
        "CreatedBy": "blah.com",
        "CreatedOn": "2017-07-14T11:34:27",
        "UpdatedOn": "2019-09-19T11:08:36",
        "UpdatedBy": "ServiceBridge",
        "Version": 4
      },
      "ExternalSystemId": null
    },
    {
      "WorkOrderNumber": "WO 370",
      "Scheduler": null,
      "Customer": {
        "Inactive": false,
        "Id": 6997686,
        "Name": "blah"
      },
      "Location": {
        "Id": 7527330,
        "Name": "Primary"
      },
      "GeoCoordinates": null,
      "CoordinatesCaptured": null,
      "Contact": {
        "Id": 7329676,
        "Name": "blah"
      },
      "ThirdPartyBillPayer": null,
      "IsMarketingCampaignSetByLead": false,
      "MarketingCampaign": {
        "Id": 115748,
        "Name": "Home Advisor"
      },
      "JobCategory": null,
      "SalesRepresentative": {
        "Id": 242299,
        "Name": "blah"
      },
      "DefaultEquipment": null,
      "Description": "50' downspout",
      "Status": "Completed",
      "IsInvoiced": true,
      "Branch": {
        "Id": 145945,
        "Name": "VA"
      },
      "Team": {
        "Id": 177761,
        "Name": "VB-Truck 1 (5'\"-6\" Combo)"
      },
      "TeamMembers": [
        {
          "EmployeeId": 242200,
          "UserId": 179580,
          "FirstName": "blah",
          "LastName": "blah",
          "Email": "blah.com",
          "Title": ""
        }
      ],
      "ConfirmationStatus": "None",
      "WorkOrderDate": "2017-06-28T00:00:00",
      "DateFinished": "2017-06-28T21:31:20",
      "ScheduledTime": 1051,
      "EstimatedDuration": 0,
      "ArrivalWindow": 0,
      "EarliestArrival": null,
      "LatestDeparture": null,
      "Notes": "Replace 50' of downspout for client using 11 a elbows",
      "PrivateNotes": null,
      "InvoiceNotes": null,
      "ReminderType": "None",
      "ReminderValue": 0,
      "ReminderMessage": null,
      "WorkOrderLines": [
        {
          "Id": 22952669,
          "ParentId": null,
          "Inventory": {
            "Id": 1688245,
            "SKU": "2X3­-AE­-ALU­-WHT",
            "Name": "2x3\" Aluminum White A Elbow",
            "Type": "Product"
          },
          "Price": 5.0,
          "Quantity": 15.0,
          "Description": "A Elbows are typically used to attach a downspoutto the face of a structure. They are also used on other areas of a downspout enabling it to conform to the contour of a structure.",
          "IsTaxable": false,
          "Tax": null
        },
        {
          "Id": 22952604,
          "ParentId": null,
          "Inventory": {
            "Id": 1688247,
            "SKU": "2X3­-DS­ALU­-WHI",
            "Name": "2x3\" Aluminum White Downspout",
            "Type": "Product"
          },
          "Price": 5.0,
          "Quantity": 50.0,
          "Description": "Downspouts carry rainwater from the gutter to the ground.",
          "IsTaxable": false,
          "Tax": null
        }
      ],
      "CustomFields": [
        {
          "Name": "CC Referred By",
          "Value": ""
        },
        {
          "Name": "E3 Electric:",
          "Value": ""
        },
        {
          "Name": "W3 Yard Sign Posted",
          "Value": ""
        },
        {
          "Name": "P2 Materials Checked",
          "Value": ""
        },
        {
          "Name": "P3 Photos & Diagrams Included",
          "Value": ""
        },
        {
          "Name": "W8 Referrals given to Customer",
          "Value": ""
        },
        {
          "Name": "E2 Ladders Needed:",
          "Value": ""
        },
        {
          "Name": "P4 Priority List",
          "Value": "False"
        },
        {
          "Name": "P Material Box",
          "Value": ""
        },
        {
          "Name": "E4 Takedown",
          "Value": ""
        },
        {
          "Name": "W6 Describe Delays",
          "Value": ""
        },
        {
          "Name": "W7 Final walk around/Payment Taken",
          "Value": ""
        },
        {
          "Name": "W5 Amount of  Delay Due To Work Obstacles",
          "Value": ""
        },
        {
          "Name": "W Tools/Materials visually inspected",
          "Value": ""
        },
        {
          "Name": "E Roof Pitch",
          "Value": ""
        },
        {
          "Name": "E1 Roof Material ",
          "Value": ""
        },
        {
          "Name": "CC1 Marketing Source Correction",
          "Value": ""
        },
        {
          "Name": "CC4 Estimate Summary Correction",
          "Value": ""
        },
        {
          "Name": "S Walk Around Done",
          "Value": ""
        },
        {
          "Name": "S1 All Expectations Set In Writing/Photos",
          "Value": ""
        },
        {
          "Name": "S2 I Feel Est. Will Close In",
          "Value": ""
        },
        {
          "Name": "S3 I went for",
          "Value": ""
        },
        {
          "Name": "E5 Movement Difficulty",
          "Value": ""
        },
        {
          "Name": "CC3 Time Lost ",
          "Value": ""
        },
        {
          "Name": "S4 Est Rating",
          "Value": ""
        },
        {
          "Name": "S6 Reason Client Chose our Company",
          "Value": ""
        },
        {
          "Name": "S5 Solutionist notes",
          "Value": ""
        },
        {
          "Name": "W1 Called in Rought",
          "Value": ""
        },
        {
          "Name": "W2 initial walk around completed",
          "Value": ""
        },
        {
          "Name": "W4 Safety Concerns/Description",
          "Value": ""
        },
        {
          "Name": "W9 Client Rating",
          "Value": ""
        },
        {
          "Name": "S7 Follow Up Notes",
          "Value": ""
        },
        {
          "Name": "CC5 Reasons for Area of Improvement",
          "Value": ""
        },
        {
          "Name": "CC2 Est. Scheduling Area of Improvement",
          "Value": ""
        },
        {
          "Name": "P1 Man Hours",
          "Value": ""
        }
      ],
      "Id": 19390520,
      "Metadata": {
        "CreatedBy": "ServiceBridge-API",
        "CreatedOn": "2017-06-28T16:20:50",
        "UpdatedOn": "2019-09-19T11:08:36",
        "UpdatedBy": "ServiceBridge",
        "Version": 18
      },
      "ExternalSystemId": null
    },

1 Ответ

0 голосов
/ 01 февраля 2020

Не уверен, в чем может быть ваша проблема.

Я изменил последние две строки вашего JSON примера, чтобы он был действительным:

enter image description here

и внесли некоторые незначительные изменения в ваш опубликованный код.

Я также сохранил JSON в файле вместо ячейки рабочего листа.

После этого JSON обработан без ошибок.

Обратите внимание, что ваш код не ставит правильные заголовки столбцов и перезаписывает себя. Я оставил это для вас, чтобы исправить.

Option Explicit
Sub doJSON()
    Dim JSON As Object
    Dim FSO As FileSystemObject, TS As TextStream
    Dim strJSON As String

    Dim ws As Worksheet
    Dim i As Long
    Dim Item As Variant

Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("D:/Users/Ron/Desktop/New Text Document.json")

strJSON = TS.ReadAll

Set JSON = parsejson(strJSON)

Set ws = Worksheets("Sheet2")

i = 3

ws.Cells(2, 1) = "WorkOrderNumber"
ws.Cells(2, 2) = "Customer Name"
ws.Cells(2, 3) = "Location Name"
ws.Cells(2, 4) = "IsInvoiced"
ws.Cells(2, 5) = "Team"
ws.Cells(2, 6) = "WorkOrderDate"
ws.Cells(2, 7) = "DateFinished"
ws.Cells(2, 8) = "ScheduledTime"
ws.Cells(2, 9) = "EstimatedDuration"
ws.Cells(2, 10) = "Notes"
ws.Cells(2, 11) = "PrivateNotes"
ws.Cells(2, 1) = "SalesRepresentative"
ws.Cells(2, 2) = "Description"
ws.Cells(2, 3) = "Status"
ws.Cells(2, 4) = "IsInvoiced"
ws.Cells(2, 5) = "Team"
ws.Cells(2, 6) = "WorkOrderDate"
ws.Cells(2, 7) = "DateFinished"
ws.Cells(2, 8) = "ScheduledTime"
ws.Cells(2, 9) = "EstimatedDuration"
ws.Cells(2, 10) = "Notes"
ws.Cells(2, 11) = "PrivateNotes"
ws.Cells(2, 12) = "CreatedBy"
ws.Cells(2, 13) = "CreatedOn"
ws.Cells(2, 14) = "UpdatedOn"
ws.Cells(2, 15) = "UpdatedBy"
ws.Cells(2, 16) = "Version"

For Each Item In JSON("Data")
    ws.Cells(i, 1) = Item("WorkOrderNumber")
    ws.Cells(i, 2) = Item("Customer")("Name")
    ws.Cells(i, 3) = Item("Location")("Name")
    ws.Cells(i, 4) = Item("Location")("Name")
    ws.Cells(i, 5) = Item("Location")("Name")
    ws.Cells(i, 6) = Item("WorkOrderDate")
    ws.Cells(i, 7) = Item("DateFinished")
    ws.Cells(i, 8) = Item("ScheduledTime")
    ws.Cells(i, 9) = Item("EstimatedDuration")
    ws.Cells(i, 10) = Item("Notes")
    ws.Cells(i, 11) = Item("PrivateNotes")
    ws.Cells(i, 1) = Item("SalesRepresentative")("Name")
    ws.Cells(i, 2) = Item("Description")
    ws.Cells(i, 3) = Item("Status")
    ws.Cells(i, 4) = Item("IsInvoiced")
    ws.Cells(i, 5) = Item("Team")("Name")
    ws.Cells(i, 6) = Item("WorkOrderDate")
    ws.Cells(i, 7) = Item("DateFinished")
    ws.Cells(i, 8) = Item("ScheduledTime")
    ws.Cells(i, 9) = Item("EstimatedDuration")
    ws.Cells(i, 10) = Item("Notes")
    ws.Cells(i, 11) = Item("PrivateNotes")
    ws.Cells(i, 12) = Item("Metadata")("CreatedBy")
    ws.Cells(i, 13) = Item("Metadata")("CreatedOn")
    ws.Cells(i, 14) = Item("Metadata")("UpdatedOn")
    ws.Cells(i, 15) = Item("Metadata")("UpdatedBy")
    ws.Cells(i, 16) = Item("Metadata")("Version")

    i = i + 1

Next

End Sub

enter image description here

Ошибка, которую вы видите, обычно возникает из-за ошибки в JSON , Я подозреваю, что или, возможно, поскольку вы вставили JSON в ячейку листа, возможно, JSON длиннее, чем ограничение в 32 767 символов ячейки, и, следовательно, недопустимо.

Если JSON слишком велик, чтобы поместиться в ячейку, я предлагаю вам сохранить его в файле и получить к нему доступ с помощью FileSystemObject (или другого метода). Если это не проблема, я бы внимательно проверил вывод JSON на наличие ошибок.

...