Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do JSON queries return object if there is one element, list if more than one?

I had to rewrite a python script from python2 to python 3 to solve the encoding problems I had the easiest way. I had to move from mysqldb to pymysql which seemed to use same syntax. I accessed the pymysql's github[1] site and following examples I noticed that when query result was one element it returned a JSON object but when it returns more than one, it returns a list.

Wouldn't it be more consistent to return always a list with 0, 1 or whichever number of elements? Why is it done this way?

Note: to avoid this behavior in pymysql just remove the cursorclass parameter from:

# Connect to the database
connection = pymysql.connect(host='localhost',user='user',
passwd='passwd', db='db', charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)

[1] https://github.com/PyMySQL/PyMySQL/

like image 983
XiR_ Avatar asked Sep 28 '22 17:09

XiR_


People also ask

Which of these functions returns result as a single JSON array?

JSON_ARRAYAGG() returns a result set as a single JSON array, and JSON_OBJECTAGG() returns a result set as a single JSON object. For more information, see Section 12.20, “Aggregate Functions”.

Can one key have multiple values in JSON?

JSON array can store multiple values. It can store string, number, boolean or object in JSON array. In JSON array, values must be separated by comma.

How do you Unnest extract nested JSON data in BigQuery?

With Holistics's modeling layer, you can let your end-user have access to data in nested JSON arrays by: Write a SQL model to unnest repeated columns in BigQuery into a flat table. Set a relationship between this derived SQL model with the base model. Add the derived SQL model in a dataset to expose it to your end user.

Which of the following clause can format any result set returned by SQL query as JSON text?

Format query results as JSON, or export data from SQL Server as JSON, by adding the FOR JSON clause to a SELECT statement.


1 Answers

According to JSON API specification, this behaviour was due to a breaking change in v1.0rc1:

BREAKING CHANGE: Singular resource objects SHOULD now be be represented with JSON objects instead of arrays. This allows for symmetrical representations in request and response documents, as well as PUT/POST requests and PATCH operations. It also simplifies implementations which do not support batch operations (i.e. they can allow an object and not an array).

You can have a look here

like image 124
javierfdezg Avatar answered Oct 04 '22 18:10

javierfdezg