在Python中用类创建JSON

时间:2017-05-10 10:20:20

标签: python json

我需要创建一个名为def add_co (existing owner name, new_attribute , attribute content) 的JSON类库。它必须从其所有者获取属性,如名称,制造和年份。我想把它变成一个未知的属性:

import json

class JCarOwner:

    CarOwner = []

    def __init__(self,name,manufacture=None,production_year=None):
        super(JCarOwner, self).__init__()
        self.CarOwner.append(json.dumps({"Owner_Name": name, "Car_Manufacture": manufacture, "Production_Year": production_year}))

    def COsave(filename):
        JCarOwner.CarOwner.dumps(filename,separators=(',', ':'))

    def COload(filename):
        JCarOwner.CarOwner.append(json.load(filename))

    def DispInfo(Car_Owner):

        for owner in JCarOwner.CarOwner:

            CO = json.load(owner)
            if CO[owner]["Owner_Name"]==Car_Owner:
                print(CO[owner])


jane = JCarOwner("Jane","Mazda",2016)
bob = JCarOwner("bob")     

JCarOwner.DispInfo(jane)

但我真的不知道如何。这是我的代码(更正):

AttributeError: 'str' object has no attribute 'read'

错误:

class ControllerName extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('my_model');
    }

    public function index() {
        $queryName = $_GET['query_string']
        // e.g. $queryName = 'customer'

        //Use the query string and append to method to pass to Model function
        $result = $this->my_model->$queryName._get_query(); //???

       //e.g. $result = $this->my_model->customer_get_query();
    }
}

1 个答案:

答案 0 :(得分:1)

使用self.CarOwner代替普通CarOwner

 def __init__(self,name,manufacture,production_year):
   super(JCarOwner, self).__init__()

   self.CarOwner.append(json.dumps({"Owner_Name": name, "Car_Manufacture": manufacture, "Production_Year": production_year}))

请尝试遵循某些python约定。