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
@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:
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:
I think the result you want may be:
or:
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:
For beginners, the above code may not be easy to understand. Let’s write the first function in a more idiotic way:
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:Obviously not in compliance with the regulations, so guess:
That’s what you want.
How to do it
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 dictionaryUse
json
module to convertjson
module 將data
轉為json_data
tojson_data
Write to file
(1) Convert
data
to the desired form: list of dictionaryThe method of the first part is quite different, I chose to make it first
names
This list:Actually this is similar to:
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:
First use
for d in data
to iterate over each pair infor d in data
來迭代data
中的一個一個 pair, 然後使用zip
, and then usezip
to combine the project name with the corresponding 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 convertjson
module 將data
轉為json_data
tojson_data
The second part, transfer out
json_data
, 這相當容易, 使用dumps
can be done, please refer to json.dumpssort_keys
: 會排序 json 中object
The keys inside can be set or notindent
: Set indentationseparators
: 設定 json 輸出的分隔符號,','
用於分隔項目,': '
Used to separate keys and valuesensure_ascii
: 設為False
, don’t use unicode escape when printing(3) Write to file
Nothing special, use
with
處理文件開關, 利用print(file=XXX)
outputQuestions I answered: Python-QA