0

I have a table in which one column we have json array data. in some rows this json is very big (with 10000+ json objects) like below. wanted to know is there any way just to select first 250 objects from the array-

[
   {
      "product":"Vegetable",
      "name":"Potato",
      "price":"$60.00"
   },
   {
      "product":"Fruit",
      "name":"Mango",
      "price":"$3.30"
   },
   {
      "product":"Milk",
      "name":"Milk",
      "price":"$1.08"
   },
.....10,000
]
1
  • What is the name of the column? What is the datatype of the column? What is the name of the database table that the column is in? Commented May 29, 2020 at 14:35

2 Answers 2

1

Well I investigated the question, and I found one can use json_query to select single entries from the JSON.

CREATE TABLE json_table ( JSON varchar(1024) NOT NULL , constraint CK_JSON_IS_JSON check (JSON is json));

insert into json_table columns (JSON) values ('[ { "product":"Vegetable", "name":"Potato", "price":"$60.00" }, { "product":"Fruit", "name":"Mango", "price":"$3.30" }, { "product":"Milk", "name":"Milk", "price":"$1.08" }]');

select json_query(JSON, '$[0]'), 
       json_query(JSON, '$[1]'), 
       json_query(JSON, '$[2]'), 
       json_query(JSON, '$[3]') 
from json_table;

This selects entries 0 to 3, with 3 not being found and being NULL.

You could probably stitch together a database stored procedure to return a list of the first n entries in the JSON.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Adder, is there any way to select subset 1-250 in one go like $[0-250}
I did not find a way to do that yet.
I found the sql but it is working fine data retun by subset is less than 4000 but if its more then it is returning null - select json_query(json, '$[0 to 250]' RETURNING clob with wrapper ) from json_table
1

An analytic function such as ROW_NUMBER() might be used within the subquery to determine the restriction, and then JSON_ARRAYAGG() and JSON_OBJECT() combination might be added to get back the reduced array :

SELECT JSON_ARRAYAGG(
                     JSON_OBJECT('product' VALUE product, 
                                 'name'    VALUE name,
                                 'price'   VALUE price) ) AS "Result"
  FROM
  (
   SELECT t.*, ROW_NUMBER() OVER (ORDER BY 1) AS rn
     FROM tab
    CROSS JOIN
     JSON_TABLE(jsdata, '$[*]' COLUMNS (
                 product VARCHAR(100) PATH '$.product',
                 name    VARCHAR(100) PATH '$.name',
                 price   VARCHAR(100) PATH '$.price'
                )
     ) t
   )
 WHERE rn <= 250 

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.