Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

json extract string traits that are nested

This is a part of the json statement.

{
  "customer": {
    "spendingHold": false,
    "createdAt": "2023-03-08T00:00:00.000Z",
    "addresses": [
      {
        "country": "USA",
        "preferences": {
          "contact": {
            "allowed": {
              "mail": true
            }
          }
        },
        "city": "Place",
        "postalCode": "11111",
        "street1": "123 Circle",
        "street2": null,
        "id": "1234567890",
        "type": "home",
        "region": "ST",
        "primary": true
      }
    ],
      "contact": {
        "allowed": {
          "times": null,
          "transactional": true
        }
      }
    },
    "creationSource": "created",
}
}

I can extract customer and creationSource with

SELECT
JSON_EXTRACT_SCALAR(json, "$.customer.spendingHold") AS spending_hold,
FROM dataset

But I am having difficulty trying to get traits like addresses and those in it like country, preferences, contact, etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My desired output should look like:

spendingHold createdAt country mail city
false 2023-03-08T00:00:00.000Z USA true Place

>Solution :

You can consider below query

WITH dataset AS (
  SELECT '''
  -- put your json string here.
  ''' json
)
SELECT JSON_VALUE(json, "$.customer.spendingHold") AS spending_hold,
       JSON_VALUE(json, "$.customer.createdAt") AS createdAt,
       JSON_VALUE(address, '$.country') AS country,
       JSON_VALUE(address, '$.preferences.contact.allowed.mail') AS mail,
       JSON_VALUE(address, '$.city') AS city
  FROM dataset, UNNEST(JSON_QUERY_ARRAY(json, '$.customer.addresses')) address;

Query results

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading