import json


from scrapy import Item

from amazon_spider.utils.common import convert_str


def loads(s):
    if type(s) is bytes:
        s = s.decode()
    t = json.loads(s)
    if 'body' in t.keys():
        t['body'] = bytes(t['body'], encoding='utf-8')
    return t


def dumps(obj):
    meta = obj['meta']
    for k in meta.keys():
        if issubclass(type(meta[k]), Item):
            meta[k] = dict(meta[k])
    if 'body' in obj.keys():
        obj['body'] = obj['body'].decode()
    if 'headers' in obj.keys():
        obj['headers'] = convert_str(obj['headers'])
    return json.dumps(obj)
