jsonparser icon indicating copy to clipboard operation
jsonparser copied to clipboard

How to get key by index?

Open Azmekin opened this issue 1 year ago • 3 comments

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

Azmekin avatar Aug 30 '23 11:08 Azmekin

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

buger avatar Aug 30 '23 14:08 buger

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 avatar May 15 '24 15:05 fracasula

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 :+1:

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))
}

fracasula avatar May 15 '24 15:05 fracasula