File: parse.py

package info (click to toggle)
cataclysm-dda 0.H-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 710,808 kB
  • sloc: cpp: 524,019; python: 11,580; sh: 1,228; makefile: 1,169; xml: 507; javascript: 150; sql: 56; exp: 41; perl: 37
file content (39 lines) | stat: -rw-r--r-- 1,297 bytes parent folder | download
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
import json

from .parser import parsers


def parse_json_object(json, origin):
    """
    Extract strings from the JSON object.
    Silently ignores JSON objects without "type" key.
    Raises exception if the JSON object contains unrecognized "type".
    """
    if "type" in json and type(json["type"]) is str:
        json_type = json["type"].lower()
        if json_type in parsers:
            try:
                parsers[json_type](json, origin)
            except Exception as E:
                print("Exception when parsing JSON data type \"{}\""
                      .format(json_type))
                raise E
        else:
            raise Exception("Unrecognized JSON data type \"{}\""
                            .format(json_type))


def parse_json_file(file_path):
    """Extract strings from the specified JSON file."""
    with open(file_path, encoding="utf-8") as fp:
        json_data = json.load(fp)

    try:
        json_objects = json_data if type(json_data) is list else [json_data]
        for json_object in json_objects:
            parse_json_object(json_object, file_path)
    except Exception as E:
        print("Error in JSON object\n'{0}'\nfrom file: '{1}'".format(
            json.dumps(json_object, indent=2), file_path))
        print(E)
        exit(1)