how to make lua table key in order - json

my test code:
local jsonc = require "jsonc"
local x = {
a = 1,
b = 2,
c = 3,
d = 4,
e = 5,
}
for k, v in pairs(x) do
print(k,v)
end
print(jsonc.stringify(x))
output:
a 1
c 3
b 2
e 5
d 4
{"a":1,"c":3,"b":2,"e":5,"d":4}
someone help:
from for pairs output, lua store table by key hash order, how can i change it?
i need output: {"a":1,"b":2,"c":3,"d":4,"e":5}
thanks

Lua tables can't preserve the order of their keys. There are two possible solutions.
You can store the keys in a separate array and iterate through that whenever you need to iterate through the table:
local keys = {'a', 'b', 'c', 'd', 'e'}
Or, instead of a hash table, you can use an array of pairs:
local x = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
}

Related

MySQL merge json field with new data while removing duplicates, where the json values are simple scalar values

Suppose that I have a MySQL table with a JSON field that contains only numbers, like this (note: using MySQL 8):
CREATE TABLE my_table (
id int,
some_field json
);
Sample data:
id: 1
some_field: [1, 2, 3, 4, 5]
id: 2
some_field: [3, 6, 7]
id: 3
some_field: null
I would like to merge another array of data with the existing values of some_field, while removing duplicates. I was hoping that this might work, but it didn't:
update my_table set some_field = JSON_MERGE([1, 2, 3], some_field)
The result of this would be:
id: 1
some_field: [1, 2, 3, 4, 5]
id: 2
some_field: [1, 2, 3, 6, 7]
id: 3
some_field: [1, 2, 3]
Considering you have 3 records in your table and you want to merge 1 and 2 as mentioned in your example.
I hope JavaScript is suitable to follow through for you.
// Get both the records
const records = db.execute(“SELECT id, some_field FROM my_table WHERE id=1 OR id=2”);
// You get both the rows.
// Merging row1, you can either use the Set data structure if you’re dealing with numbers like your example, or you could loop using a map and use the spread operator if using JSON. Since your object is an array, I’ll just be explaining to merge 2 arrays.
records[0].some_field = Array.from(new Set(records[0].some_field + record[1].some_field))
// Same for second record.
records[1].some_field = Array.from(new Set(records[0].some_field + record[1].some_field))
// Now update both the records in the database one by one.

How to check if json keys are from an allowed set in PostgreSQL?

'{"a":1, "b":2, "c":3}'::jsonb ?& array['a', 'b'] checks if right hand side, an array of text, is contained by the top-level keys of the left hand side.
How can I check the opposite? That is, whether the keys of the json string are from a known set of texts.
You can get the keys of your object with json(b)_object_keys and collect them into an array. Then use the array contains operator:
array(SELECT jsonb_object_keys('{"a":1, "b":2, "c":3}'::jsonb)) <# array['a', 'b']
Alternatively, you could use a subquery on the keys and conjugate tests against the array (equivalent to the NOT EXISTS check by #GMB):
SELECT bool_and(k = ANY(array['a', 'b'])) FROM jsonb_object_keys(object) as k
(online demo)
You can use jsonb_object_keys() and ANY like so:
select 1
from jsonb_object_keys(t.js) o(x)
where not x = ANY(ar)
Here is how to use this in a query:
with t as (
select '{"a":1, "b":2, "c":3}'::jsonb js, array['a', 'b', 'c'] ar
union all select '{"a":1, "b":2, "z":3}'::jsonb js, array['a', 'b'] ar
)
select
js,
ar,
not exists(
select 1
from jsonb_object_keys(t.js) o(x)
where not x = ANY(ar)
) res
from t
Yields:
js | ar | res
:----------------------- | :------ | :-----
{"a": 1, "b": 2, "c": 3} | {a,b,c} | true
{"a": 1, "b": 2, "z": 3} | {a,b} | false

Django. How i can get list of Users with a duplicate?

i have array like this: [1, 1, 1, 2, 3]. How i can get users with a duplicate? For example this query return list without duplicate
list= User.objects.filter(id__in=[1, 1, 1, 2, 3])
for example it will be users with id's:
1,
2,
3
but i need list of users like this:
1,
1,
1,
2,
3
list = []
for x in [1, 1, 1, 2, 3]:
list.append(User.objects.filter(id=x)
It this what you mean? I don't quite understand the spacing.
Get your queryset sorted in the right order. .order_by('id) for ascending by id (which may be the default anyway). Then iterate over the queryset with code to make extra operations with the same object (or a copy thereof) as dictated by the list of IDs.
idlist = [1, 1, 1, 2, 3]
queryset = User.objects.filter(id__in = idlist ).order_by('id')
for object in queryset:
for _ in range( idlist.count( object.id))
do_something_with( object)
Note, this is only one DB call (one queryset), unlike the accepted answer which does one DB query for each element in the id list. Not good.

How to select row using array of object in NodeJs

I have database with game square (called game):
id | x | y | isGold
I program I have array of coords like this:
var test = [
{x:1, y:2},
{x:2, y:4}
]
I want select all rows from game table somethink like this:
Select * from game where x and y in (?) where isGold = true, [test] ...
But problem is, that I don't know how to create select with object. I can transform my array to anything, how can I make a query for this problem?
If you use mysqljs/mysql npm package try this:
Select * from game where (x, y) IN (?) where isGold = true, [[[1, 2], [2, 4]]
Look at the doc
https://github.com/mysqljs/mysql#performing-queries
Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
Nested arrays are turned into grouped lists (for bulk inserts), e.g.
[['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')

pluck based on common attribute (rails)

I have a table Followership, in which every record has attributes user_id and follower_id.
I can do something like this:
Followership.limit(10).pluck('user_id, follower_id)
But this will give me result like this [[1,A][2,B],[3,C],[4,A],[1,B][2,D]]
I want to convert the above array in such a way that all arrays with same user_ids should be merged in following form [user_id, FOLLOWER_ID(S)]
i.e;
[[1,[A,B]][2,[B,D]],[3,C],[4,A]]
Here user_id = 1 has two followers A,B and user_id = 2 has two followers B,D
How to do this?
As pointed out by Sergio, you could use group_by with the array that you get after pluck, for example:
arr = [[1,'A'],[2,'B'],[3,'C'],[4,'A'],[1,'B'],[2,'D']]
a.group_by(&:first).map { |k, v| [k, v.map(&:last)] }
#=> [[1, ["A", "B"]], [2, ["B", "D"]], [3, ["C"]], [4, ["A"]]]
Another approach
a = [[1,'A'],[2,'B'],[3,'C'],[4,'A'],[1,'B'][2,'D']]
h = Hash.new { |h, k| h[k] = [] }
a.inject(h) { |sum, t| sum[t[0]] << t[1]; sum}.to_a