Dive into Code

Discover code snippets, tutorials, and programming insights

Python

SQL query to json list in python

<p>convert sql query to json list in python with pyodbc</p>

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import pyodbc
import json

MS_SQL_Host = "host"
MS_SQL_Db = "db_name"
MS_SQL_User = "user"
MSSQL_Paswd = "pass"

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        # 👇️ if passed in object is instance of Decimal
        # convert it to a string
        if isinstance(obj, Decimal):
            return str(obj)
        # 👇️ otherwise use the default behavior
        return json.JSONEncoder.default(self, obj)

def write_json_data(data, filename):
    with open("{}.json".format(filename), "w", encoding="utf-8") as f:
        # json.dump(data, f, ensure_ascii=False, indent=4, cls=DecimalEncoder)
        json.dump(data, f, ensure_ascii=False, cls=DecimalEncoder)


def get_data(query, name):
    mssql_connection = pyodbc.connect(
        "DRIVER={SQL Server};SERVER="
        + MS_SQL_Host
        + ";DATABASE="
        + MS_SQL_Db
        + ";UID="
        + MS_SQL_User
        + ";PWD="
        + MSSQL_Paswd
    )
    mssql_cursor = mssql_connection.cursor()
    results = []
    mssql_cursor.execute(query)
    columns = [column[0] for column in mssql_cursor.description]
    for row in mssql_cursor.fetchall():
        data = dict(zip(columns, row))
        results.append(data)
    mssql_cursor.close()
    mssql_connection.close()
    return write_json_data(results, name)

data = get_data("sql_query", 'data')
Django

Django json decimal encoder

<p>Convert decimal to string for json&nbsp; file</p>

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import json

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        # 👇️ if passed in object is instance of Decimal
        # convert it to a string
        if isinstance(obj, Decimal):
            return str(obj)
        # 👇️ otherwise use the default behavior
        return json.JSONEncoder.default(self, obj)


def write_json_data(data, filename):
    with open("{}.json".format(filename), "w", encoding="utf-8") as f:
        # json.dump(data, f, ensure_ascii=False, indent=4, cls=DecimalEncoder)
        json.dump(data, f, ensure_ascii=False, cls=DecimalEncoder)
jQuery

jQuery ajax with authorization token bearer with jwt

<p>Example of jquery ajax call with authorization bearer token&nbsp;</p>

javascript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$.when($.ajax({
        url: 'url',
        method:  'get',
        datatype: 'json',
        headers: {"Authorization": "Bearer " + localStorage.getItem('token')}

      })).then(function( response, textStatus, jqXHR ) {
      console.info(response);
      var obj = response;
      console.info(obj)
      
    }).catch(function(err){
      $.each(err.responseJSON, function(index, value){
        console.info(index, value);
    })
})