question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Prettify JSON - MySQL/MariaDB

See original GitHub issue

Recently I found the need to “prettify” my JSON columns in my database. https://stackoverflow.com/questions/2614862/how-can-i-beautify-json-programmatically

Before (yeesh!)

{"city": "Vassar", "referer": "https://www.google.com/", "state": "MI", "zip": "48768", "country": "US", "latitude": "43.0000", "longitude": "-84.0000", "useragent": { "isBot": false,   "browser": "Safari",   "version": "12.0",   "os": "OS X",   "platform": "iPhone"}}

After (Ahhh!)

{
    "city": "Vassar",
    "referer": "https://www.google.com/",
    "state": "MI",
    "zip": "48768",
    "country": "US",
    "latitude": "43.0000",
    "longitude": "-84.0000",
    "useragent": {
        "isBot": false,
        "browser": "Safari",
        "version": "12.0",
        "os": "OS X",
        "platform": "iPhone"
    }
}

Currently, with Sequelize, the JSON datatype columns are stored as LONGTEXT and the objects are stored as hard to read one liners.

I decided to create global hooks on afterUpdate and afterInsert to autodetect the JSON columns on all models, JSON.stringify’ing with 4 spaces. Now it’s permanently stored as beautiful human readable data, ya dig?

Two writes and one read will occur on models that contain JSON columns.

(Advertisement: https://github.com/HeidiSQL/HeidiSQL viewer rocksfor MySQL/MariaDB/MSSQL! Use it!)

**Full Config **

  var Sequelize = require('sequelize'),
    sequelize = new Sequelize(process.env.db_name, process.env.db_user, process.env.db_pass, {
    host: process.env.db_host,
    port: process.env.db_port,
    dialect: 'mariadb',
    dialectOptions: {
      timezone: process.env.db_timezone
    },
    pool: {
      min: 0,
      max: 2,
      idle: 10000
    },
    define: {
      charset: 'utf8',
      timestamps: false,
      hooks: {
        afterCreate: (model, fn) => {
          formatCols(model)
        },
        afterUpdate: (model, fn) => {
          formatCols(model)
        }
      }
    },
    benchmark: false,
    logging: false
  })
function formatCols(model) {
    for(let json_key in model.rawAttributes) {
      if(model.rawAttributes[json_key].type.key.toUpperCase() == 'JSON') {
        var obj = app.get('functions').objEscapeDblQuotes(model[json_key]),
          json_val = JSON.stringify(obj, null, app.get('json spaces'))
        json_val = json_val.replace(/\\([\s\S])|(")/g, "\\$1$2")
        json_val = json_val.replace(/'/g, "\\'")
        var raw_sql_string = "UPDATE `" + model.constructor.name + "` SET `" + json_key + "` = \'" + json_val + "\' WHERE id = " + model.id
        app.get('sequelize').query(raw_sql_string).then(([results, metadata]) => {
        })
      }
    }
}

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:11 (11 by maintainers)

github_iconTop GitHub Comments

1reaction
knoxcardcommented, Aug 9, 2019

@papb - agreed, too much for Sequelize, already moved it over to the mariadb driver npm. https://github.com/MariaDB/mariadb-connector-nodejs/issues/68

0reactions
papbcommented, Aug 7, 2019

@knoxcard Hmm, I see… Still, I think it’s a bit too specific to be built-in in sequelize. Perhaps you can write a plugin or something?

Also:

@papb - wouldn’t you still need two beforeHooks: beforeUpdate() and beforeUpdate()?

What did you really mean here?

Read more comments on GitHub >

github_iconTop Results From Across the Web

EXPLAIN FORMAT=JSON Differences From MySQL - MariaDB
MariaDB's EXPLAIN JSON output is different from MySQL's. Here's a list of differences. (Currently they come in no particular order). Contents. Attached ...
Read more >
Making MariaDB understand MySQL JSON
MariaDB and MySQL JSON formats are not the same. In MySQL, the JSON type is a native type, while in MariaDB JSON is...
Read more >
Format JSON Documents for Easier Readability in MySQL
In MySQL, the JSON_PRETTY() function provides pretty-printing of JSON values. It returns the JSON values in a nicely formatted way, ...
Read more >
Select from a mariaDB table into JSON format - Serge Frezefond
MariaDB and MySQL are not currently JSON friendly databases. The usage of JSON in MySQL is almost inexistent with the excetion of the...
Read more >
MySQL 8.0 Reference Manual :: 11.5 The JSON Data Type
Optimized storage format. JSON documents stored in JSON columns are converted to an internal format that permits quick read access to document elements....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found