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

How to get key by index? #266

Open
Azmekin opened this issue Aug 30, 2023 · 3 comments
Open

How to get key by index? #266

Azmekin opened this issue Aug 30, 2023 · 3 comments

Comments

@Azmekin
Copy link

Azmekin commented Aug 30, 2023

I saw func "eachKey". Do you have func for get key by index?

@buger
Copy link
Owner

buger commented Aug 30, 2023

Hi! No, you will have to iterate till needed index, and then return early. But overall performance wise it will be the same.

@fracasula
Copy link

you will have to iterate till needed index, and then return early

How do you return early though? Same for ArrayEach, how do I just get the first element without having ArrayEach invoke the callback for each element of the array? There is no way to stop it.

@fracasula
Copy link

you will have to iterate till needed index, and then return early

How do you return early though? Same for ArrayEach, how do I just get the first element without having ArrayEach invoke the callback for each element of the array? There is no way to stop it.

I just realized that this works too and solves my problem 👍

var jsonData = []byte(`{
	"hello":[{},{},   "{fake-object}" ],   
	"batch" : [    
		{ 
			"userId": 123,
			"context": {"library":{
				"name":"analytics-go",
				"version": "1.2.3"
			}}
		},
		{ },
		{},
		{"inner" : { } }
	] 
}`)

func TestVersionFromEvent(t *testing.T) {
	value, dataType, _, err := jsonparser.Get(jsonData, "batch", "[0]", "context", "library", "version")
	require.NoError(t, err)
	require.Equal(t, jsonparser.String, dataType)
	require.Equal(t, "1.2.3", string(value))
}

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