2

Following snowflake query returns the JSON structure but output is sorted by the keys. How not to sort by the keys but retains the order? Is there any parameter setting that needs to be set?

select
object_construct
(
  'entity',  'XYZ',
  'allowed',  'Yes',
  'currency', 'USD',
  'statement_month','July, 2020'
 )

Output: --it sorts by the keys

{
  "allowed": "Yes",
  "currency": "USD",
  "entity": "XYZ",
  "statement_month": "July, 2020"
}

Expected Output: --same order as specified

{
  "entity": "XYZ",
  "allowed": "Yes",
  "currency": "USD",
  "statement_month": "July, 2020"
}
Samir
  • 21
  • 1
  • 4

3 Answers3

5

JSON is an unordered collection of name and values. Order cannot be guaranteed in JSON.

The constructed object does not necessarily preserve the original order of the key-value pairs.

You can do it like as below

SELECT mytable:entity::string as entity,
mytable:allowed::string as allowed,
mytable:currency::string as currency,
mytable:statement_month::string as statement_month
from
(select
object_construct
(
  'entity',  'XYZ',
  'allowed',  'Yes',
  'currency', 'USD',
  'statement_month','July, 2020'
 ) mytable);
Rajib Deb
  • 1,496
  • 11
  • 30
  • Thanks for the comment, but goal is to produce a JSON output. I think what you've is tabular. – Samir Aug 14 '20 at 13:52
0

Unfortunately, no

Usage notes: https://docs.snowflake.com/en/sql-reference/functions/object_construct.html#usage-notes

The constructed object does not necessarily preserve the original order of the key-value pairs.

same for PARSE_JSON Usage notes: https://docs.snowflake.com/en/sql-reference/functions/parse_json.html#usage-notes

The order of the key-value pairs in the string produced by TO_JSON is not predictable.

Monem_منعم
  • 336
  • 2
  • 10
  • Correct. That's what I know but just wanted to see if any ways out there.Thanks for the response though! – Samir Aug 14 '20 at 13:53
0

The order was found to be maintained when using object_construct(*):

WITH base AS (               
SELECT 'XYZ' "entity", 'Yes' "allowed", 'USD' "currency", 'July, 2020' "statement_month")
SELECT object_construct(*) FROM base;
Vijay Nair
  • 69
  • 1
  • 2