1

In my table, i've got a column where I save an array of jsons as a string, like this:

[
  {
  "id":0,
  "stops":[
     {
        "Id":0,
        "field1":"data1",
        "field2":"data2"
     }
  ],
  "time":"01:00:00"
  },

  {
  "id":2,
  "stops":[
     {
        "Id":0,
        "field1":"data1",
        "field2":"data2"
     }
  ],
  "time":"01:00:00"
  },
]

I want to count the number of jsons in this array. The database is in PostgreSQL 9.6.1.

3
  • In your example, is the expected output 2?4? Which database? (Mysql, sql server, etc?) Commented May 4, 2018 at 21:37
  • Sorry, the database is in PostgreSQL 9.6.1, and the output in this case, is 2. Commented May 7, 2018 at 13:34
  • 1
    json_array_length()? Commented May 7, 2018 at 13:42

1 Answer 1

2

You can use the json_array_length() function to count, but if your column is of text type you will need to cast the column to become a json type, as follows:

json_array_length(cast(your_table.column_name as json))

Also, if you need to access your "stops" field, you could use json_array_elements() and do it like this:

json_array_elements( cast(your_table.column_name as json))->'Stops'

And to access even further, like fields inside "stop", you can just use the same function again:

json_array_elements( (json_array_elements( cast(your_table.column_name as json)))->'Stops')->'field1'

Hope I could help.

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

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.