Login

parse json string

Author:
agusmakmun
Posted:
August 11, 2019
Language:
Python
Version:
Not specified
Tags:
django json templatetags utils parser
Score:
1 (after 1 ratings)

function to parse the string text into json format

 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
47
48
49
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import ast
import json


def parse_json_string(text, default={}):
    """
    function to parse the json string
    into json parse or dict
    :param `text` is the value of text model to parse.
    :paran `default` is default output, eg: {}, []
    :return json loads or dict.
    """
    output = default

    if not text:
        return default

    if isinstance(text, list) or isinstance(text, dict):
        return text

    try:
        output = json.loads(text)
    except json.decoder.JSONDecodeError:
        try:
            output = ast.literal_eval(text)
        except Exception:
            # invalid format
            pass

    if type(default) == type(output):
        return output

    return default


"""
from .utils import parse_json_string


class Post(models.Model):
    json_data = models.TextField()

    @property
    def get_json_data(self):
        return parse_json_string(self.json_data, default={})
"""

More like this

  1. "Magic Link" Management Command by webology 3 weeks, 4 days ago
  2. Closest ORM models to a latitude/longitude point by simonw 3 weeks, 5 days ago
  3. Log the time taken to execute each DB query by kennyx46 3 weeks, 5 days ago
  4. django database snippet by ItsRLuo 1 month ago
  5. Serialize a model instance by chriswedgwood 2 months ago

Comments

Please login first before commenting.