Home  >  Q&A  >  body text

python - 数据库提取出的数据转json

我从数据库中取出两列数据得到

data = [['美国', 46], ['英国', 27], ['中国', 26]]

如何转换为json格式的文件

{
    {
        name: '美国',
        value: 46
    },
    {
        name: '英国',
        value: 27
    },
    {
        name: '中国',
        value: 26
    },
}

求相关的python代码。最好能附上注释,本人初学者,多包涵,真的不是很会这个问题。

PHP中文网PHP中文网2741 days ago734

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:30:56

    I think the result you want may be:

    [
        {
            "name": "美国",
            "value": 46
        },
        {
            "name": "英国",
            "value": 27
        },
        {
            "name": "中国",
            "value": 26
        }
    ]

    or:

    {
        "data": [
            {
                "name": "美国",
                "value": 46
            },
            {
                "name": "英国",
                "value": 27
            },
            {
                "name": "中国",
                "value": 26
            }
        ]
    }
    import json
    
    
    def convert_to_json_string_1(data):
        return json.dumps([{'name': i[0], 'value': i[1]} for i in data], indent=4)
        
    def convert_to_json_string_2(data):
        return json.dumps({'data': [{'name': i[0], 'value': i[1]} for i in data]}, indent=4)

    The json format actually serializes Python objects into a plain text file (for Python)
    json.dumps function converts (serializes) a python object into a json string. Indent means using 4 spaces to indent Enter, this string is also a normal string, you can:

    with open('some-file.json', 'w') as handle:
        handle.write(convert_to_json_string_1(data)

    For beginners, the above code may not be easy to understand. Let’s write the first function in a more idiotic way:

    def convert_to_json_string_1(data):
        ret = []  # 需要序列化的列表
        for i in data:
            tmp = {'name': i[0], 'value': i[1]}  # 通过data的每一个元素构造一个字典
            ret.append(tmp)
        ret = json.dumps(ret, indent=4)
        return ret

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:30:56

    About the question

    @pylego There is a problem. Your output example is not standard json (for the standard definition of json, please refer to: Introducing JSON). {} is a js object, similar to Python's dictionary. It should be composed of key-value pairs. , the example you gave:

    {
        {
            name: '美国',
            value: 46
        },
        {
            name: '英国',
            value: 27
        },
        {
            name: '中国',
            value: 26
        },
    }

    Obviously not in compliance with the regulations, so guess:

    [
        {
            "name": "美国",
            "value": 46
        },
        {
            "name": "英国",
            "value": 27
        },
        {
            "name": "中国",
            "value": 26
        }
    ]

    That’s what you want.

    How to do it

    import json
    
    data = [['美国', 46], ['英国', 27], ['中国', 26]]
    names = 'name value'.split()
    
    data = [dict(zip(names, d)) for d in data]
    
    with open('out.json', 'w') as writer:
        json_data = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False) 
        print(json_data, file=writer)

    Everyone should have similar methods in terms of practice, which can be roughly divided into three parts:

    • Convert data to the desired form: list of dictionary

    • Use json module to convert json module 將 data 轉為 json_data to json_data

    • Write to file

    (1) Convert data to the desired form: list of dictionary

    The method of the first part is quite different, I chose to make it first namesThis list:

    names = 'name value'.split()

    Actually this is similar to:

    names = ['name', 'value']

    is the same, but I really like using split because it is faster to write (when there are many projects, you don’t need to put so many quotation marks).

    Then I use a list comprehension to create a list of dictionary:

    data = [dict(zip(names, d)) for d in data]

    First use for d in data to iterate over each pair in for d in data 來迭代 data 中的一個一個 pair, 然後使用 zip, and then use zip to combine the project name with the corresponding value:

    # zip
    '美国',  46
       |     |      =>  ('name', '美国'), ('value', 46)
    'name'  'value'

    Then dict can take in an iterables (each item is a key-value pair, such as a two-element tuple) and create a dictionary.

    (2) Use json module to convert json module 將 data 轉為 json_data to json_data

    The second part, transfer out json_data, 這相當容易, 使用 dumps can be done, please refer to json.dumps

    json_data = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False) 
    • sort_keys: 會排序 json 中 object The keys inside can be set or not

    • indent: Set indentation

    • separators: 設定 json 輸出的分隔符號, ',' 用於分隔項目, ': ' Used to separate keys and values

    • ensure_ascii: 設為 False, don’t use unicode escape when printing

    (3) Write to file

    Nothing special, use with 處理文件開關, 利用 print(file=XXX) output


    Questions I answered: Python-QA

    reply
    0
  • Cancelreply