buger/jsonparser

How to get key by index?

Azmekin opened this issue · 3 comments

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

buger commented

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

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.

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