Reputation: 33
I have a JSON string:
{
"entry_offset" : 180587225765,
"entry_size" : 54003,
"created_time" : 1577500878,
"additional_meta" : {
"geohash64" : 5637765837143565,
"mime_type" : "image/jpg"
}
And I have converted it to Lua Table using Tarantool's module json:
table = json.decode(JSONstring)
Then I want to insert the table to Tarantool with ID = 1
box.space.somespace:insert{1, table}
The result is like this when I select the table which added to Tarantool database in JSON form:
Cannot access values through key
I can only access to table[1] and table[2]: table[1] is the ID = 1 while table[2] is all the JSON string. Which means I can't access the Values of JSON with Keys: table['entry_offset'], table['entry_size'], .... return nil when I try to access them
So how can I insert a Lua table to Tarantool and then access the values through its keys?
Thanh you so much for helping!!!
Upvotes: 1
Views: 690
Reputation: 555
You are basically inserting a wrapping tuple into the space, not table
object itself, so when you do:
obj = box.space.somespace:get{1}
you get your tuple back, not table
. That said if you want to access table
's fields using keys, you just need to index that obj like this:
table = obj[2]
print(table.entry_offset)
Once you get used to it, check out tarantool space format feature with its tomap
/frommap
functions. Here is basic example, which may help you:
box.cfg{}
box.schema.create_space('test', {if_not_exists = true})
box.space.test:create_index('pk', {unique = true, if_not_exists = true, parts = {1, 'unsigned'}})
box.space.test:format({
{ name = 'id', 'unsigned' },
{ name = 'entry_offset', 'unsigned' },
{ name = 'entry_size', 'unsigned' },
{ name = 'created_time', 'unsigned' },
{ name = 'additional_meta', 'map' },
})
json = require('json')
obj_json = [[{
"entry_offset" : 180587225765,
"entry_size" : 54003,
"created_time" : 1577500878,
"additional_meta" : {
"geohash64" : 5637765837143565,
"mime_type" : "image/jpg"
}}]]
obj = json.decode(obj_json)
obj.id = 1
tuple = box.space.test:frommap(obj)
box.space.test:insert(tuple)
result = box.space.test:get({1}):tomap()
print(result.additional_meta.mime_type)
Or, for more advanced serialization approach, take a look at avro-schema with its flatten
/unflatten
methods. There are examples in README
Upvotes: 2