How to sort a table with a value in json table in another json table

Hi.
I’m wondering that would be the best way to sort a table with os.time in it so it would go from the lowest to the highest os.time.
Basically, imagine my JSON table something like that:

[
  {
    "desc": "{\"Desc\":\"Test1\",\"Duration\":30,\"Time\":1584374400,\"}"
    }
  },
  {
    "desc": "{\"Desc\":\"Test2\",\"Duration\":30,\"Time\":1584453600,\"}"
    }
  }
]

There’s Time in that “table”. How would I get that json table as whole in order by that time value?

I know there’s a function table.sort, but I don’t know how would I use that function comp.

Thank you!

Can’t you sort it before turning it into JSON? Or does JSON not keep the same order?

JSON doesn’t keep the same order.

Can you maybe do some hacky string manipulation, find the time value, and reorder each desc

How would I do that manipulation?

If it’s consistently in that format, something like this should work. You would have to do it before converting the outer table to JSON. I don’t know why you said it doesn’t keep the same order, because it definitely should keep the array’s order.

table.sort(outer, function(table1, table2)
	local json1, json2 = table1.desc, table2.desc
	return tonumber(json1:match('Time\": ?(%d+)')) < tonumber(json2:match('Time\": ?(%d+)'))
end)

Basically, just check for digits after "Time": and compare them.

2 Likes

I actually got it somehow :smiley:, but I’ll still take a look at your solution, because, at the moment, mine is very inefficient but still does it’s job.

Also second thing, there can be more json tables inside the main json table, not just 2. My table was just an example.

Yeah, table.sort has that covered. The function will run for every pair of elements within the table.

2 Likes

Basically, my solution is that it takes time from each json table and sorts it. After that, it would loop through the main json table and compare each time with each time in that table where only time is. If it matches, it would replace it.

1 Like

If your method works fine, no need to use my method. I was just showing a potential way to do it with string patterns, and both should work just as well.

2 Likes

Yeah, I’ll still mark yours as the solution since it’s more efficient. Thank you for answering!

1 Like