Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Json data include collections, how to get value of collections. thanks. #280

Closed
poplarfeng opened this issue Jan 2, 2025 · 5 comments
Closed

Comments

@poplarfeng
Copy link

I want get the first "id" value of schedule->2024->6th, how to use the vba-json?

json as belows.

{
"code": "0001",
"message": "success",
"schedule": {
"2024": {
"6th":[
{
"id": "1699",
"strong_base_id": "688",
"schedule": "2024-06",
},
{
"id": "1700",
"strong_base_id": "688",
"schedule": "2024-06",
}
]
}
}
}

@aholden10
Copy link

aholden10 commented Jan 2, 2025 via email

@DecimalTurn
Copy link

DecimalTurn commented Jan 2, 2025

There seems to be 2 issues with your JSON:

  1. The colon in the following line:
"6th":[

The colon there is actually a Fullwidth Colon instead of a regular colon.

  1. Presence of trailing commas after the schedule keys. This is not supported in the regular JSON specs, so you'll need to remove them.

If I fix those and format your json to be more readable, we get the following:

{
    "code": "0001",
    "message": "success",
    "schedule": {
        "2024": {
            "6th": [
                {
                    "id": "1699",
                    "strong_base_id": "688",
                    "schedule": "2024-06"
                },
                {
                    "id": "1700",
                    "strong_base_id": "688",
                    "schedule": "2024-06"
                }
            ]
        }
    }
}

With that, your VBA code could look like the following:

    Dim JsonString As String
    JsonString = "{""code"": ""0001"",""message"": ""success"",""schedule"": {""2024"": {""6th"": [{""id"": ""1699"",""strong_base_id"": ""688"",""schedule"": ""2024-06""},{""id"": ""1700"",""strong_base_id"": ""688"",""schedule"": ""2024-06""}]}}}"

    Dim Json As Dictionary
    Set Json = ParseJson(JsonString)
    
    Debug.Print Json("schedule")("2024")("6th")(1)("id")

Note that the use of (1) is how you are getting the first element of the collection.

Also, it might be a better practice to use the Item method to avoid using the default member:

Debug.Print Json.Item("schedule").Item("2024").Item("6th").Item(1).Item("id")

@poplarfeng
Copy link
Author

Thanks,DecimalTurn. Your reply answered my question. Thanks again.

@DecimalTurn
Copy link

@poplarfeng my pleasure! Feel free to close the issue as resolved.

@poplarfeng
Copy link
Author

resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants