JSONSerializer   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 55
rs 10
c 2
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A mentions_to_JSON() 0 16 1
A mentions_to_JSON_dict() 0 8 3
B mentions_from_JSON() 0 24 3
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
from __future__ import unicode_literals
5
from .ds import Document
6
from .odin import Mention
7
import json
8
9
10
class JSONSerializer(object):
11
    """
12
    Utilities for serialization/deserialization of data structures.
13
    
14
    """
15
    @staticmethod
16
    def mentions_to_JSON_dict(mentions):
17
        jdict = dict()
18
        docs = {m._doc_id:m.document.to_JSON_dict() for m in mentions}
19
        mns = {m.id:m.to_JSON_dict() for m in mentions}
20
        jdict["documents"] = docs
21
        jdict["mentions"] = mns
22
        return jdict
23
24
    @staticmethod
25
    def mentions_to_JSON(mentions):
26
        """
27
        Serializes a list of `processors.odin.Mention` to a JSON string.
28
29
        Parameters
30
        ----------
31
        mentions : [processors.odin.Mention]
32
            A list of `processors.odin.Mention` to be serialized to JSON.
33
34
        Returns
35
        -------
36
        str
37
            A JSON serialization (str) of a list of `processors.odin.Mention`.
38
        """
39
        return json.dumps(JSONSerializer.mentions_to_JSON_dict(mentions), sort_keys=True, indent=4)
40
41
    @staticmethod
42
    def mentions_from_JSON(jdict):
43
        """
44
        Loads `processors.odin.Mention` from a dictionary of JSON data (`jdict`).
45
46
        Parameters
47
        ----------
48
        jdict : dict
49
            A dictionary of JSON data encoding a list of `Mention`s and their corresponding `Document`s.
50
51
        Returns
52
        -------
53
        [processors.odin.Mention]
54
            A list of `processors.odin.Mention`
55
        """
56
        # build map of documents
57
        docs_dict = {doc_id:Document.load_from_JSON(djson) for (doc_id, djson) in jdict["documents"].items()}
58
        # deserialize mentions
59
        mns_json = jdict["mentions"]
60
        mentions = []
61
        for mjson in mns_json:
62
            m = Mention.load_from_JSON(mjson, docs_dict)
63
            mentions.append(m)
64
        return mentions
65