AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 78821863
Accepted
Lord OfTheRing
Lord OfTheRing
Asked: 2024-08-01 23:43:00 +0800 CST2024-08-01 23:43:00 +0800 CST 2024-08-01 23:43:00 +0800 CST

VBA JsonConverter.ParseJson Analisar Jason me dando erro de tipo incompatível

  • 772

Tenho um valor Json abaixo em string groupsjasontext e gosto de analisar id, member.value, role.value usando JsonConverter.ParseJson. Como eu vou fazer isso ? Tentei mostrar via messagebox o campo id e estou recebendo o erro Type Mismatch

    Set JsonData = JsonConverter.ParseJson(groupsjasontext)
    tempName = JsonData("id")(0)
    MsgBox (tempName)
    {
  "schemas": [
    "urn:ietf:params:scim:api:messages:2.0:ListResponse"
  ],
  "totalResults": 3,
  "startIndex": 1,
  "itemsPerPage": 3,
  "Resources": [
    {
      "schemas": [
        "urn:ietf:params:scim:schemas:core:2.0:Group",
        "urn:sap:params:scim:schemas:extension:sac:2.0:group-custom-parameters"
      ],
      "id": "d3094970-ce7e-4794-b9e2-f84817b7c820",
      "meta": {
        "resourceType": "Group",
        "created": "2024-05-21T17:53:06.808Z",
        "lastModified": "2024-05-21T17:53:06.808Z",
        "location": "/api/v1/scim2/Groups/d3094970-ce7e-4794-b9e2-f84817b7c820"
      },
      "displayName": "AHI_VW_ALL_REGION",
      "urn:sap:params:scim:schemas:extension:sac:2.0:group-custom-parameters": {
        "description": "View Mode ALL REGION"
      }
    },
    {
      "schemas": [
        "urn:ietf:params:scim:schemas:core:2.0:Group",
        "urn:sap:params:scim:schemas:extension:sac:2.0:group-roles",
        "urn:sap:params:scim:schemas:extension:sac:2.0:group-custom-parameters"
      ],
      "id": "bef561ee-5a1e-420e-a1e\n4-4f624c96af6e",
      "meta": {
        "resourceType": "Group",
        "created": "2024-07-25T14:17:53.215Z",
        "lastModified": "2024-08-01T14:31:29.632Z",
        "location": "/api/v1/scim2/Groups/bef561ee-5a1e-420e-a1e4-4f624c96af6e"
      },
      "displayName": "TEAM_TEST",
      "members": [
        {
          "value": "f27dcbb9-df9a-46b2-b23a-3b35d5a8bdff",
          "type": "User",
          "display": "Test_FirstName1 TEST_Familyname1",
          "$ref": "/api/v1/scim2/Users/f27dcbb9-df9a-46b2-b23a-3b35d5a8bdff"
        }
      ],
      "urn:sap:params:scim:schemas:extension:sac:2.0:group-roles": {
        "roles": [
          {
            "value": "PROFILE:t.4:VIEW_USER",
            "display": "VIEW_USER"
          }
        ]
      },
      "urn:sap:params:scim:schemas:extension:sac:2.0:group-custom-parameters": {
        "description": "Team Test"
      }
    },
    {
      "schemas": [
        "urn:ietf:params:scim:schemas:core:2.0:Group",
        "urn:sap:params:scim:schemas:extension:sac:2.0:group-custom-parameters"
      ],
      "id": "1edd9227-c8de-486e-93f6-69396524c792",
      "meta": {
        "resourceType": "Group",
        "created": "2024-05-21T17:51:49.808Z",
        "lastModified": "2024-05-21T17:53:06.121Z",
        "location": "/api/v1/scim2/Groups/1edd9227-c8de-486e-93f6-69396524c792"
      },
      "displayName": "AHI_VW_EURAM\n",
      "urn:sap:params:scim:schemas:extension:sac:2.0:group-custom-parameters": {
        "description": "View mode EURAM"
      }
    }
  ]
}
json
  • 3 3 respostas
  • 57 Views

3 respostas

  • Voted
  1. Haluk
    2024-08-02T00:39:39+08:002024-08-02T00:39:39+08:00

    Usando JSonParser, os valores necessários podem ser extraídos da sua string JSON de amostra da seguinte maneira;

    Sub Test()
        Dim strJSON As String, JSon As Object, id As String, membersValue As String, rolesValue As String
        
        strJSON = "{""schemas"":[""urn:ietf:params:scim:schemas:core:2.0:Group"",""urn:sap:params:scim:schemas:extension:sac:2.0:group-roles"",""urn:sap:params:scim:schemas:extension:sac:2.0:group-custom-parameters""],""id"":""bef561ee-5a1e-420e-a1e\n4-4f624c96af6e"",""meta"":{""resourceType"":""Group"",""created"":""2024-07-25T14:17:53.215Z"",""lastModified"":""2024-08-01T14:31:29.632Z"",""location"":""/api/v1/scim2/Groups/bef561ee-5a1e-420e-a1e4-4f624c96af6e""},""displayName"":""TEAM_TEST"",""members"":[{""value"":""f27dcbb9-df9a-46b2-b23a-3b35d5a8bdff"",""type"":""User"",""display"":""Test_FirstName1 TEST_Familyname1"",""$ref"":""/api/v1/scim2/Users/f27dcbb9-df9a-46b2-b23a-3b35d5a8bdff""}],""urn:sap:params:scim:schemas:extension:sac:2.0:group-roles"":{""roles"":[{""value"":""PROFILE:t.4:VIEW_USER"",""display"":""VIEW_USER""}]},""urn:sap:params:scim:schemas:extension:sac:2.0:group-custom-parameters"":{""description"":""Team Test""}}"
          
        Set JSon = ParseJson(strJSON)
    
        id = JSon("id")
        
        membersValue = JSon("members")(1)("value")
        
        rolesValue = JSon("urn:sap:params:scim:schemas:extension:sac:2.0:group-roles")("roles")(1)("value")
    
        
        MsgBox "id = " & id & vbCrLf & "members.value = " & membersValue & vbCrLf & "roles.value = " & rolesValue
    End Sub
    
    
    • 1
  2. Tim Williams
    2024-08-02T00:40:21+08:002024-08-02T00:40:21+08:00

    A idchave está associada a um único valor, não a um objeto ou array, então

    tempName = JsonData("id")(0)
    MsgBox (tempName)   'no parens as noted in BigBen's comment
    

    deveria estar

    tempName = JsonData("id")
    MsgBox tempName
    
    • 1
  3. Best Answer
    PeterT
    2024-08-02T03:46:24+08:002024-08-02T03:46:24+08:00

    Achei muito mais fácil acessar especificamente diferentes partes de um objeto JSON individualmente em cada etapa. Isto ajudou a evitar a maioria dos problemas e confusões entre os diferentes objetos (Dicionários e Coleções). Eu uso essa referência o tempo todo, ela provou ser de grande ajuda.

    Então, com base nesse conselho e usando a referência vinculada, criei o código de teste abaixo para mostrar como acessar diferentes partes da sua estrutura JSON e executar loops quando for apropriado.

    Option Explicit
    
    Sub test()
        Dim strJSON As String
        strJSON = GetJSONString
        
        Dim json As Object
        Set json = ParseJson(strJSON)
        
        Dim resources As Collection
        Set resources = GetCollection(json, "Resources")
        
        Dim junk As Collection
        Set junk = GetCollection(json, "junk")
        
        Dim resource As Dictionary
        For Each resource In resources
            Debug.Print "----- Resource:"
            Dim schemas As Collection
            Set schemas = GetCollection(resource, "schemas")
            
            Dim i As Long
            For i = 1 To schemas.Count
                Debug.Print "   Schema(" & i & ") = " & schemas(i)
            Next i
            
            Dim id As String
            id = resource("id")
            
            Dim meta As Dictionary
            Set meta = GetDictionary(resource, "meta")
            If Not meta Is Nothing Then
                Dim metaEntry As Variant
                For Each metaEntry In meta
                    Debug.Print "   Meta Entry: " & metaEntry & " = " & meta(metaEntry)
                Next metaEntry
            End If
            
            Dim displayName As String
            displayName = resource("displayName")
            
            Dim members As Collection
            Set members = GetCollection(resource, "members")
            If Not members Is Nothing Then
                Dim member As Variant
                Debug.Print "   member count = " & members.Count
                For i = 1 To members.Count
                    Dim memberEntry As Dictionary
                    Set memberEntry = members(i)
                    Dim entryKey As Variant
                    For Each entryKey In memberEntry
                        Debug.Print "   For member(" & i & "): " & entryKey & " = " & memberEntry(entryKey)
                    Next entryKey
                Next i
            End If
        Next resource
    End Sub
    
    Function GetCollection(ByRef jsonObj As Object, ByVal entryName As String) As Collection
        On Error Resume Next
        Set GetCollection = jsonObj(entryName)
        If GetCollection Is Nothing Then
            Debug.Print "The requested object " & entryName & " does not exist in the referenced Collection"
        End If
    End Function
    
    Function GetDictionary(ByRef jsonObj As Object, ByVal entryName As String) As Dictionary
        On Error Resume Next
        Set GetDictionary = jsonObj(entryName)
        If GetDictionary Is Nothing Then
            Debug.Print "The requested object " & entryName & " does not exist in the referenced Dictionary"
        End If
    End Function
    
    Function GetJSONString() As String
        Dim fileHandle As Integer
        Dim filename As String
        filename = "C:\temp\test.json"
        fileHandle = FreeFile
        Open filename For Input As FreeFile
        GetJSONString = Input(LOF(fileHandle), fileHandle)
        Close fileHandle
    End Function
    
    • 0

relate perguntas

  • PostgreSQL: como validar campos JSON?

  • filtragem jq em chave específica e agrupamento de valores em uma única célula csv

  • Elasticsearch: Erro ao criar réplicas em cluster de 2 nós

  • Mensagem de erro do Apex de vendas em uma linha em que nada foi alterado

  • Como usar a função de tecla XSLT 3.0

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve