Tôi có một đối tượng JSON rất lớn mà tôi cần chia thành các đối tượng nhỏ hơn và viết các đối tượng nhỏ hơn đó vào tệp.
Dữ liệu mẫu
raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]'
Đầu ra mong muốn [trong ví dụ này, chia một nửa dữ liệu] [In this example, split the data in half]
output_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}]
output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
Mã hiện tại
import pandas as pd
import itertools
import json
from itertools import zip_longest
def grouper[iterable, n, fillvalue=None]:
args = [iter[iterable]] * n
return zip_longest[fillvalue=fillvalue, *args]
raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]'
#split the data into manageable chunks + write to files
for i, group in enumerate[grouper[raw, 4]]:
with open['outputbatch_{}.json'.format[i], 'w'] as outputfile:
json.dump[list[group], outputfile]
Đầu ra hiện tại của tệp đầu tiên "OutputBatch_0.json" of first file "outputbatch_0.json"
["[", "{", "\"", "s"]
Tôi cảm thấy như tôi đang làm cho điều này khó khăn hơn nhiều so với nó cần phải có.
Bạn đang ở đây vì khi bạn cố gắng tải và phân tích tệp JSON với nhiều đối tượng JSON trong Python, bạn đã nhận được một lỗi.
output_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}]
output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
3. Lý do là phương thức & nbsp; json.load [] chỉ có thể xử lý một đối tượng JSON duy nhất.Tệp không hợp lệ nếu nó chứa nhiều đối tượng JSON. Khi bạn cố gắng tải và phân tích tệp JSON với nhiều đối tượng JSON, mỗi dòng chứa JSON hợp lệ, nhưng nói chung, nó không phải là JSON hợp lệ vì không có danh sách cấp cao hoặc định nghĩa đối tượng. Chúng ta chỉ có thể gọi JSON là JSON hợp lệ khi có danh sách cấp cao nhất hoặc định nghĩa đối tượng.
Ví dụ: bạn muốn đọc tệp JSON sau đây, lọc một số dữ liệu và lưu trữ nó vào tệp JSON mới.
{"id": 1, "name": "Ault", "class": 8, "email": ""} {"id": 2, "name": "john", "class": 8, "email": ""} {"id": 3, "name": "josh", "class": 8, "email": ""} {"id": 4, "name": "emma", "class": 8, "email": ""}
Nếu tệp của bạn chứa một danh sách các đối tượng JSON và bạn muốn giải mã một đối tượng một-một lần, chúng tôi có thể làm điều đó. Để tải và phân tích tệp JSON với nhiều đối tượng JSON, chúng ta cần tuân theo các bước dưới đây:Load and parse a JSON file with multiple JSON objects we need to follow below steps:
- Tạo một danh sách trống có tên
4output_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}] output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
- Đọc từng dòng tệp vì mỗi dòng chứa JSON hợp lệ. tức là, đọc một đối tượng JSON tại một thời điểm.
- Chuyển đổi từng đối tượng JSON thành Python
5 bằng cách sử dụngoutput_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}] output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
6output_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}] output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
- Lưu từ điển này vào một danh sách có tên là respress jsonlist.
Hãy để xem ví dụ bây giờ.
import json
studentsList = []
print["Started Reading JSON file which contains multiple JSON document"]
with open['students.txt'] as f:
for jsonObj in f:
studentDict = json.loads[jsonObj]
studentsList.append[studentDict]
print["Printing each JSON Decoded Object"]
for student in studentsList:
print[student["id"], student["name"], student["class"], student["email"]]
Output::
Started Reading JSON file which contains multiple JSON document Printing each JSON Decoded Object 1 Ault 8 2 john 8 3 josh 8 4 emma 8
Vậy bạn nghĩ như thế nào?
Tôi muốn nghe từ bạn. Bạn nghĩ gì về bài viết này? Hoặc có thể tôi đã bỏ lỡ một trong những cách để phân tích nhiều đối tượng JSON từ một tệp, dù bằng cách nào, hãy cho tôi biết bằng cách để lại một bình luận bên dưới.leaving a comment below.
Ngoài ra, hãy cố gắng giải bài tập Python JSON để hiểu rõ hơn về việc làm việc với dữ liệu JSON trong Python.
Bài tập và câu đố Python
Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.
- Hơn 15 bài tập và câu đố dành riêng cho chủ đềTopic-specific Exercises and Quizzes
- Mỗi bài tập chứa 10 câu hỏi
- Mỗi bài kiểm tra chứa 12-15 mcq
Chuyển đổi chuỗi JSON sang đối tượng Pandas.
Bất kỳ đường dẫn chuỗi hợp lệ đều được chấp nhận. Chuỗi có thể là một url. Các sơ đồ URL hợp lệ bao gồm HTTP, FTP, S3 và Tệp. Đối với URL tệp, một máy chủ được dự kiến. Một tập tin cục bộ có thể là:
output_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}]
output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
7.Nếu bạn muốn vượt qua trong một đối tượng đường dẫn, Pandas chấp nhận bất kỳ
output_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}]
output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
8 nào.Theo đối tượng giống như tệp, chúng tôi đề cập đến các đối tượng bằng phương thức
output_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}]
output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
9, chẳng hạn như xử lý tệp [ví dụ: thông qua hàm tích hợp import pandas as pd
import itertools
import json
from itertools import zip_longest
def grouper[iterable, n, fillvalue=None]:
args = [iter[iterable]] * n
return zip_longest[fillvalue=fillvalue, *args]
raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]'
#split the data into manageable chunks + write to files
for i, group in enumerate[grouper[raw, 4]]:
with open['outputbatch_{}.json'.format[i], 'w'] as outputfile:
json.dump[list[group], outputfile]
0] hoặc import pandas as pd
import itertools
import json
from itertools import zip_longest
def grouper[iterable, n, fillvalue=None]:
args = [iter[iterable]] * n
return zip_longest[fillvalue=fillvalue, *args]
raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]'
#split the data into manageable chunks + write to files
for i, group in enumerate[grouper[raw, 4]]:
with open['outputbatch_{}.json'.format[i], 'w'] as outputfile:
json.dump[list[group], outputfile]
1.orentstrstrChỉ định định dạng chuỗi JSON dự kiến. Các chuỗi JSON tương thích có thể được tạo ra bởi
import pandas as pd
import itertools
import json
from itertools import zip_longest
def grouper[iterable, n, fillvalue=None]:
args = [iter[iterable]] * n
return zip_longest[fillvalue=fillvalue, *args]
raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]'
#split the data into manageable chunks + write to files
for i, group in enumerate[grouper[raw, 4]]:
with open['outputbatch_{}.json'.format[i], 'w'] as outputfile:
json.dump[list[group], outputfile]
2 với giá trị định hướng tương ứng. Tập hợp các orents có thể là:
3: Dict nhưimport pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
4import pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
5: Danh sách nhưimport pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
6import pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
7: Dict Likeimport pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
8import pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
9: Dict Likeimport pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
0["[", "{", "\"", "s"]
1: Chỉ là mảng giá trị["[", "{", "\"", "s"]
Các giá trị được phép và mặc định phụ thuộc vào giá trị của tham số typ.
Khi
2,["[", "{", "\"", "s"]
Người được phép là
3["[", "{", "\"", "s"]
Mặc định là
7import pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
Chỉ số loạt phải là duy nhất cho Orient
7.import pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
Khi
6,["[", "{", "\"", "s"]
Người được phép là
7["[", "{", "\"", "s"]
Mặc định là
9import pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
Chỉ số DataFrame phải là duy nhất cho các
7 vàimport pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
9.import pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
Các cột DataFrame phải là duy nhất cho các
7,import pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
9 vàimport pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
5.import pandas as pd import itertools import json from itertools import zip_longest def grouper[iterable, n, fillvalue=None]: args = [iter[iterable]] * n return zip_longest[fillvalue=fillvalue, *args] raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]' #split the data into manageable chunks + write to files for i, group in enumerate[grouper[raw, 4]]: with open['outputbatch_{}.json'.format[i], 'w'] as outputfile: json.dump[list[group], outputfile]
Loại đối tượng để phục hồi.
dtypeBool hoặc dict, mặc định không cóbool or dict, default NoneNếu đúng, suy ra dtypes; Nếu một lệnh của cột thành dtype, thì hãy sử dụng chúng; Nếu sai, thì don không suy ra DTYPE, chỉ áp dụng cho dữ liệu.
Đối với tất cả các giá trị
{"id": 1, "name": "Ault", "class": 8, "email": ""} {"id": 2, "name": "john", "class": 8, "email": ""} {"id": 3, "name": "josh", "class": 8, "email": ""} {"id": 4, "name": "emma", "class": 8, "email": ""}4 ngoại trừ
{"id": 1, "name": "Ault", "class": 8, "email": ""} {"id": 2, "name": "john", "class": 8, "email": ""} {"id": 3, "name": "josh", "class": 8, "email": ""} {"id": 4, "name": "emma", "class": 8, "email": ""}5, mặc định là đúng.
Đã thay đổi trong phiên bản 0.25.0: Không áp dụng cho {"id": 1, "name": "Ault", "class": 8, "email": ""}
{"id": 2, "name": "john", "class": 8, "email": ""}
{"id": 3, "name": "josh", "class": 8, "email": ""}
{"id": 4, "name": "emma", "class": 8, "email": ""}
6.Not applicable for
{"id": 1, "name": "Ault", "class": 8, "email": ""} {"id": 2, "name": "john", "class": 8, "email": ""} {"id": 3, "name": "josh", "class": 8, "email": ""} {"id": 4, "name": "emma", "class": 8, "email": ""}6.convert_axesbool, không có mặc địnhbool, default None
Cố gắng chuyển đổi các trục thành DTYPE thích hợp.
Đối với tất cả các giá trị
{"id": 1, "name": "Ault", "class": 8, "email": ""} {"id": 2, "name": "john", "class": 8, "email": ""} {"id": 3, "name": "josh", "class": 8, "email": ""} {"id": 4, "name": "emma", "class": 8, "email": ""}4 ngoại trừ
{"id": 1, "name": "Ault", "class": 8, "email": ""} {"id": 2, "name": "john", "class": 8, "email": ""} {"id": 3, "name": "josh", "class": 8, "email": ""} {"id": 4, "name": "emma", "class": 8, "email": ""}5, mặc định là đúng.
Đã thay đổi trong phiên bản 0.25.0: Không áp dụng cho {"id": 1, "name": "Ault", "class": 8, "email": ""}
{"id": 2, "name": "john", "class": 8, "email": ""}
{"id": 3, "name": "josh", "class": 8, "email": ""}
{"id": 4, "name": "emma", "class": 8, "email": ""}
6.Not applicable for
{"id": 1, "name": "Ault", "class": 8, "email": ""} {"id": 2, "name": "john", "class": 8, "email": ""} {"id": 3, "name": "josh", "class": 8, "email": ""} {"id": 4, "name": "emma", "class": 8, "email": ""}6.convert_axesbool, không có mặc địnhbool or list of str, default True
Cố gắng chuyển đổi các trục thành DTYPE thích hợp.
convert_datesbool hoặc danh sách str, mặc định truebool, default TrueNếu đúng thì các cột datelike mặc định có thể được chuyển đổi [tùy thuộc vào keep_default_dates]. Nếu sai, không có ngày nào sẽ được chuyển đổi. Nếu một danh sách các tên cột, thì các cột đó sẽ được chuyển đổi và các cột Datelike mặc định cũng có thể được chuyển đổi [tùy thuộc vào Keep_Default_Dates].
keep_default_datesbool, mặc định đúng
Nếu ngày phân tích cú pháp [convert_dates không sai], thì hãy thử phân tích các cột Datelike mặc định. Một nhãn cột là giống như dữ liệu nếu
Nó kết thúc với
0,import json studentsList = [] print["Started Reading JSON file which contains multiple JSON document"] with open['students.txt'] as f: for jsonObj in f: studentDict = json.loads[jsonObj] studentsList.append[studentDict] print["Printing each JSON Decoded Object"] for student in studentsList: print[student["id"], student["name"], student["class"], student["email"]]
Nó kết thúc với
1,import json studentsList = [] print["Started Reading JSON file which contains multiple JSON document"] with open['students.txt'] as f: for jsonObj in f: studentDict = json.loads[jsonObj] studentsList.append[studentDict] print["Printing each JSON Decoded Object"] for student in studentsList: print[student["id"], student["name"], student["class"], student["email"]]
Nó bắt đầu với
2,import json studentsList = [] print["Started Reading JSON file which contains multiple JSON document"] with open['students.txt'] as f: for jsonObj in f: studentDict = json.loads[jsonObj] studentsList.append[studentDict] print["Printing each JSON Decoded Object"] for student in studentsList: print[student["id"], student["name"], student["class"], student["email"]]
import json
studentsList = []
print["Started Reading JSON file which contains multiple JSON document"]
with open['students.txt'] as f:
for jsonObj in f:
studentDict = json.loads[jsonObj]
studentsList.append[studentDict]
print["Printing each JSON Decoded Object"]
for student in studentsList:
print[student["id"], student["name"], student["class"], student["email"]]
3, hoặcbool, default FalseĐó là
import json
studentsList = []
print["Started Reading JSON file which contains multiple JSON document"]
with open['students.txt'] as f:
for jsonObj in f:
studentDict = json.loads[jsonObj]
studentsList.append[studentDict]
print["Printing each JSON Decoded Object"]
for student in studentsList:
print[student["id"], student["name"], student["class"], student["email"]]
4.numpybool, mặc định sai
Giải mã trực tiếp đến mảng numpy. Chỉ hỗ trợ dữ liệu số, nhưng các nhãn và chỉ mục không phải là số chỉ được hỗ trợ. Cũng lưu ý rằng thứ tự JSON phải giống nhau cho mỗi thuật ngữ nếu numpy = true.bool, default FalseKhông dùng nữa kể từ phiên bản 1.0.0.
precise_floatbool, mặc định saistr, default NoneĐặt để cho phép sử dụng hàm độ chính xác cao hơn [STRTOD] khi giải mã chuỗi thành các giá trị kép. Mặc định [sai] là sử dụng chức năng tích hợp nhanh nhưng ít chính xác hơn.
date_unitstr, mặc định không cóstr, default is ‘utf-8’Đơn vị dấu thời gian để phát hiện nếu chuyển đổi ngày. Hành vi mặc định là cố gắng và phát hiện độ chính xác chính xác, nhưng nếu điều này không mong muốn thì hãy vượt qua một trong số đó, ‘ms,’ ’’ chúng tôi hoặc ’ns, để buộc phân tích cú pháp chỉ vài giây, mili giây, micro giây hoặc nano giây tương ứng.
EncodingTr, mặc định là ‘UTF-8str, optional, default “strict”Mã hóa để sử dụng để giải mã byte py3.
Encoding_errorsstr, tùy chọn, mặc định là nghiêm ngặt
Cách xử lý lỗi mã hóa. Danh sách các giá trị có thể.bool, default FalseMới trong phiên bản 1.3.0.
lineBool, mặc định saiint, optionalĐọc tệp dưới dạng đối tượng JSON trên mỗi dòng.
Chunksizeint, tùy chọn
import json
studentsList = []
print["Started Reading JSON file which contains multiple JSON document"]
with open['students.txt'] as f:
for jsonObj in f:
studentDict = json.loads[jsonObj]
studentsList.append[studentDict]
print["Printing each JSON Decoded Object"]
for student in studentsList:
print[student["id"], student["name"], student["class"], student["email"]]
6 is a context manager.Trả về đối tượng JsonReader cho Lặp lại. Xem các tài liệu JSON được chọn lọc để biết thêm thông tin về import json
studentsList = []
print["Started Reading JSON file which contains multiple JSON document"]
with open['students.txt'] as f:
for jsonObj in f:
studentDict = json.loads[jsonObj]
studentsList.append[studentDict]
print["Printing each JSON Decoded Object"]
for student in studentsList:
print[student["id"], student["name"], student["class"], student["email"]]
5. Điều này chỉ có thể được truyền nếu dòng = true. Nếu điều này là không, tệp sẽ được đọc vào bộ nhớ cùng một lúc.str or dict, default ‘infer’Cho việc giải nén dữ liệu trên đĩa. Nếu 'suy luận' và 'path_or_buf' giống như đường dẫn, thì hãy phát hiện nén từ các phần mở rộng sau: '.gz', '.bz2', '.zip', '.xz', '.zst', '.tar' , '.tar.gz', '.tar.xz' hoặc '.tar.bz2' [nếu không thì không nén]. Nếu sử dụng ‘zip, hoặc‘ tar, tệp zip phải chỉ chứa một tệp dữ liệu được đọc. Đặt thành
import json
studentsList = []
print["Started Reading JSON file which contains multiple JSON document"]
with open['students.txt'] as f:
for jsonObj in f:
studentDict = json.loads[jsonObj]
studentsList.append[studentDict]
print["Printing each JSON Decoded Object"]
for student in studentsList:
print[student["id"], student["name"], student["class"], student["email"]]
7 để không giải nén. Cũng có thể là một dict với khóa import json
studentsList = []
print["Started Reading JSON file which contains multiple JSON document"]
with open['students.txt'] as f:
for jsonObj in f:
studentDict = json.loads[jsonObj]
studentsList.append[studentDict]
print["Printing each JSON Decoded Object"]
for student in studentsList:
print[student["id"], student["name"], student["class"], student["email"]]
8 được đặt thành một trong {import json
studentsList = []
print["Started Reading JSON file which contains multiple JSON document"]
with open['students.txt'] as f:
for jsonObj in f:
studentDict = json.loads[jsonObj]
studentsList.append[studentDict]
print["Printing each JSON Decoded Object"]
for student in studentsList:
print[student["id"], student["name"], student["class"], student["email"]]
9, Started Reading JSON file which contains multiple JSON document Printing each JSON Decoded Object 1 Ault 8 2 john 8 3 josh 8 4 emma 80,
Started Reading JSON file which contains multiple JSON document Printing each JSON Decoded Object 1 Ault 8 2 john 8 3 josh 8 4 emma 81,
Started Reading JSON file which contains multiple JSON document Printing each JSON Decoded Object 1 Ault 8 2 john 8 3 josh 8 4 emma 82,
Started Reading JSON file which contains multiple JSON document Printing each JSON Decoded Object 1 Ault 8 2 john 8 3 josh 8 4 emma 83} và các cặp giá trị khóa khác được chuyển tiếp đến
Started Reading JSON file which contains multiple JSON document Printing each JSON Decoded Object 1 Ault 8 2 john 8 3 josh 8 4 emma 84,
Started Reading JSON file which contains multiple JSON document Printing each JSON Decoded Object 1 Ault 8 2 john 8 3 josh 8 4 emma 85,
Started Reading JSON file which contains multiple JSON document Printing each JSON Decoded Object 1 Ault 8 2 john 8 3 josh 8 4 emma 86, ____. Ví dụ, những điều sau đây có thể được thông qua để giải nén Zstandard bằng cách sử dụng từ điển nén tùy chỉnh:
Started Reading JSON file which contains multiple JSON document Printing each JSON Decoded Object 1 Ault 8 2 john 8 3 josh 8 4 emma 89.
Mới trong phiên bản 1.5.0: Đã thêm hỗ trợ cho các tệp .tar.Added support for .tar files.
Đã thay đổi trong phiên bản 1.4.0: Hỗ trợ Zstandard.Zstandard support.
NrowsInt, tùy chọnint, optionalSố lượng các dòng từ JsonFile được phân phối dòng phải được đọc. Điều này chỉ có thể được truyền nếu dòng = true. Nếu điều này là không, tất cả các hàng sẽ được trả lại.
Mới trong phiên bản 1.1.
Storage_OptionsDict, Tùy chọndict, optionalCác tùy chọn bổ sung có ý nghĩa cho một kết nối lưu trữ cụ thể, ví dụ: máy chủ, cổng, tên người dùng, mật khẩu, v.v. cho URL HTTP [s], các cặp giá trị khóa được chuyển tiếp đến
>>> df = pd.DataFrame[[['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']]0 dưới dạng tùy chọn tiêu đề. Đối với các URL khác [ví dụ: bắt đầu với S3: //, và GC GCS: //], các cặp giá trị khóa được chuyển tiếp đến
>>> df = pd.DataFrame[[['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']]1. Vui lòng xem
>>> df = pd.DataFrame[[['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']]2 và
>>> df = pd.DataFrame[[['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']]3 để biết thêm chi tiết và để biết thêm ví dụ về các tùy chọn lưu trữ, hãy tham khảo tại đây.
Mới trong phiên bản 1.2.0.
ReturnSseries hoặc dataFrameLoại trả về phụ thuộc vào giá trị của typ.
Ghi chú
Cụ thể với
{"id": 1, "name": "Ault", "class": 8, "email": ""} {"id": 2, "name": "john", "class": 8, "email": ""} {"id": 3, "name": "josh", "class": 8, "email": ""} {"id": 4, "name": "emma", "class": 8, "email": ""}6, nếu một
>>> df = pd.DataFrame[[['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']]5 có tên
>>> df = pd.DataFrame[[['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']]6 của chỉ mục được viết bằng
import pandas as pd
import itertools
import json
from itertools import zip_longest
def grouper[iterable, n, fillvalue=None]:
args = [iter[iterable]] * n
return zip_longest[fillvalue=fillvalue, *args]
raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]'
#split the data into manageable chunks + write to files
for i, group in enumerate[grouper[raw, 4]]:
with open['outputbatch_{}.json'.format[i], 'w'] as outputfile:
json.dump[list[group], outputfile]
2, thao tác đọc tiếp theo sẽ đặt tên >>> df = pd.DataFrame[[['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']]6 thành
import json
studentsList = []
print["Started Reading JSON file which contains multiple JSON document"]
with open['students.txt'] as f:
for jsonObj in f:
studentDict = json.loads[jsonObj]
studentsList.append[studentDict]
print["Printing each JSON Decoded Object"]
for student in studentsList:
print[student["id"], student["name"], student["class"], student["email"]]
7. Điều này là do chỉ mục cũng được >>> df.to_json[orient='split'] '{"columns":["col 1","col 2"],"index":["row 1","row 2"],"data":[["a","b"],["c","d"]]}' >>> pd.read_json[_, orient='split'] col 1 col 2 row 1 a b row 2 c d0 sử dụng để biểu thị tên
>>> df = pd.DataFrame[[['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']]6 bị thiếu và hoạt động
>>> df.to_json[orient='split'] '{"columns":["col 1","col 2"],"index":["row 1","row 2"],"data":[["a","b"],["c","d"]]}' >>> pd.read_json[_, orient='split'] col 1 col 2 row 1 a b row 2 c d2 tiếp theo không thể phân biệt giữa hai. Giới hạn tương tự gặp phải với
>>> df.to_json[orient='split'] '{"columns":["col 1","col 2"],"index":["row 1","row 2"],"data":[["a","b"],["c","d"]]}' >>> pd.read_json[_, orient='split'] col 1 col 2 row 1 a b row 2 c d3 và bất kỳ tên nào bắt đầu bằng
>>> df.to_json[orient='split'] '{"columns":["col 1","col 2"],"index":["row 1","row 2"],"data":[["a","b"],["c","d"]]}' >>> pd.read_json[_, orient='split'] col 1 col 2 row 1 a b row 2 c d4.
Ví dụ
>>> df = pd.DataFrame[[['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']]
Mã hóa/giải mã DataFrame bằng cách sử dụng JSON được định dạng
import pandas as pd
import itertools
import json
from itertools import zip_longest
def grouper[iterable, n, fillvalue=None]:
args = [iter[iterable]] * n
return zip_longest[fillvalue=fillvalue, *args]
raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]'
#split the data into manageable chunks + write to files
for i, group in enumerate[grouper[raw, 4]]:
with open['outputbatch_{}.json'.format[i], 'w'] as outputfile:
json.dump[list[group], outputfile]
3:>>> df.to_json[orient='split'] '{"columns":["col 1","col 2"],"index":["row 1","row 2"],"data":[["a","b"],["c","d"]]}' >>> pd.read_json[_, orient='split'] col 1 col 2 row 1 a b row 2 c d
Mã hóa/giải mã DataFrame bằng cách sử dụng JSON được định dạng
import pandas as pd
import itertools
import json
from itertools import zip_longest
def grouper[iterable, n, fillvalue=None]:
args = [iter[iterable]] * n
return zip_longest[fillvalue=fillvalue, *args]
raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]'
#split the data into manageable chunks + write to files
for i, group in enumerate[grouper[raw, 4]]:
with open['outputbatch_{}.json'.format[i], 'w'] as outputfile:
json.dump[list[group], outputfile]
7:>>> df.to_json[orient='index'] '{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
output_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}]
output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
0Mã hóa/giải mã một khung dữ liệu bằng cách sử dụng JSON được định dạng
import pandas as pd
import itertools
import json
from itertools import zip_longest
def grouper[iterable, n, fillvalue=None]:
args = [iter[iterable]] * n
return zip_longest[fillvalue=fillvalue, *args]
raw = '[{"id":"1","num":"2182","count":-17}{"id":"111","num":"3182","count":-202}{"id":"222","num":"4182","count":12},{"id":"33333","num":"5182","count":12}]'
#split the data into manageable chunks + write to files
for i, group in enumerate[grouper[raw, 4]]:
with open['outputbatch_{}.json'.format[i], 'w'] as outputfile:
json.dump[list[group], outputfile]
5. Lưu ý rằng các nhãn chỉ mục không được bảo tồn với mã hóa này.output_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}]
output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
1Mã hóa với lược đồ bảng
output_file1.json = [{"id":"1","num":"2182","count":-17},{"id":"111","num":"3182","count":-202}]
output_file2.json = [{"id":"222","num":"4182","count":12}{"id":"33333","num":"5182","count":12}]
2