0

I have two classes, using python 2.7 :

class Script(object):
    name = ""
    version = 0
    dependency = []

class Dependency(object):
    name = ""
    version = 0

Ending up in a list listOfScripts like this :

listOfScripts = [20, 3, [39, 2, 30, 4], 21, 4, [65, 9, 12, 5]]

How can I dump this list as json ? I want the final output to be :

[{ "name":...
"version":...
"dependency": [{"name": .., "version":..},  {"name": .., "version":..}]
}]
1
  • 3
    Can you explain structure of listOfScripts? Commented Feb 20, 2014 at 14:45

2 Answers 2

2

This will work for you:

import json

class Script(object):
    def __init__(self, name, version, dependency_list):
        self.name = name
        self.version = version
        self.dependency_list = self.parse_dependencies(dependency_list)

    def parse_dependencies(self, dep_list):
        """
        Take our dependency list and turn it into a list of Dependency objects.
        """
        dependency_list = []
        for i in xrange(0, len(dep_list), 2):
            d = Dependency(dep_list[i], dep_list[i+1])
            dependency_list.append(d)
        return dependency_list

    def output_to_json(self):
        """
        Output our self to a dict that can be used in a json.dumps()
        """
        context = {
            'name': self.name,
            'version': self.version,
            'dependencies': [c.output_to_json() for c in self.dependency_list]
        }
        return context


class Dependency(object):
    def __init__(self, name, version):
        self.name = name
        self.version = version

    def output_to_json(self):
        context = {
            'name': self.name,
            'version': self.version
        }
        return context


def make_classes_from_list(list_of_scripts):
    """
    Take your list of numbers and turn it into a list of Script
    and Dependency objects.
    """
    output = []
    for i in xrange(0, len(list_of_scripts), 3):
        s = Script(list_of_scripts[i], list_of_scripts[i+1], list_of_scripts[i+2])
        output.append(s)
    return output


listOfScripts = [20, 3, [39, 2, 30, 4], 21, 4, [65, 9, 12, 5]]
list_of_script_objects = make_classes_from_list(listOfScripts)

print(json.dumps([x.output_to_json() for x in list_of_script_objects]))

will then output:

[{"version": 3, "name": 20, "dependencies": [{"version": 2, "name": 39}, {"version": 4, "name": 30}]}, {"version": 4, "name": 21, "dependencies": [{"version": 9, "name": 65}, {"version": 5, "name": 12}]}]
Sign up to request clarification or add additional context in comments.

Comments

1
import json
class Script(object):
    def __init__(self, name, version, dependency):
        self.name = name
        self.version = version
        self.dependency = dependency
    def toJSON(self):
        return dict(name = self.name, version = self.version, dependency = self.dependency)

class Dependency(object):
    def __init__(self, name, version):
        self.name = name
        self.version = version
    def toJSON(self):
        return dict(name = self.name, version = self.version)

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj,'toJSON'):
            return obj.toJSON()
        else:
            return json.JSONEncoder.default(self, obj)

listOfScripts = [Script(20, 3, [Dependency(39, 2), Dependency(30, 4)]), 
                 Script(21, 4, [Dependency(65, 9), Dependency(12, 5)])]
print([json.dumps(x.toJSON(), cls=ComplexEncoder) for x in listOfScripts])

the output is:

['{"name": 20, "version": 3, "dependency": [{"name": 39, "version": 2}, {"name": 30, "version": 4}]}', '{"name": 21, "version": 4, "dependency": [{"name": 65, "version": 9}, {"name": 12, "version": 5}]}']

1 Comment

Thanks mate, now I have two versions ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.