Login

parse json string

Author:
agusmakmun
Posted:
August 11, 2019
Language:
Python
Version:
Not specified
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.