High Performance SQLite is an excellent and immersive course, featuring real-time typed commands and valuable edge case explanations. I highly recommend it for enhancing your SQLite skills.Han-Hsun Liu
Build with and integrate SQLite into your production applications.
I've made my test data available for you to use and follow along.
(keyboard clanking) We're gonna look at a couple of ways that you can create JSON. The first is the one that we've been doing, which is just you pass in some value to the json function, that's one way to create JSON. There are two other methods that work pretty well and we have touched briefly on both of them, json_object. And with json_object, the first thing that you pass in is the label. And the second thing is the value. They call it the label, that's the name of the argument. I think we all call it the key, so you pass in key value. The other thing you can do is you can do json_array and you can pass in variadic. I think that's how you say it, variadic arguments. And that will give you an array. Now, you can also do something like select json_array_length. That is another JSON function, that doesn't create JSON like these three do. But while we're here talking about arrays, let's do that. So if you were to pass in a quoted string, is that gonna be right? Is that gonna be right? Okay. So we have to go back to our value argument and our path argument question, the video that we did on that. And if we flip over here and we look at json_array_length, we see that it does accept json. So if we were to pass in a string, SQLite is going to try to turn that into JSON. So we're good. So we can do 1, 2, 3, 4, and if we close it out, it'll tell us, yes, there are five elements in this array. You can pass through a path as well. That one's not gonna work because there's nothing there. But let's say, we did, we called this array, foo. And we said that the array is foo and we were to close this out. I don't think that's gonna work. That's zero because it's not actually an array. However, if we were to pass in a path, remember all paths start with a dollar sign and then a dot and an object path, or in our case, we'll do a dot and foo. So we're saying, all right, go into this object, go into the foo key and tell me how long that array is. Five elements. There you go. So just a quick hit on creating JSON objects. You can use json or jsonb. You can use json_array, jsonb_array, json_object, jsonb_object, depending on what you need back, whether text or binary. And if you want to inspect the length of an array, you can use json_array_length.