Hướng dẫn how to save array to json in python? - làm thế nào để lưu mảng vào json trong python?

Tôi muốn tạo một tệp JSON như

{
"a":["12","34","23",...],
"b":["13","14","45",....],
.
.
.
}

Khóa sẽ đến từ danh sách:

lis = ['a','b',...]

và giá trị từ truy vấn SQL "Chọn ID từ" + I, trong đó tôi đang lặp lại qua danh sách thông qua "I". Truy vấn này chỉ cần trả về ID cột.

Đây là mã mẫu:

lis = ['a','b','c']
len_obj = len[lis]

with open["Dataset.json", 'w'] as file:
    for i in lis:
        file.write[i]
        obj_query = i + '_query'       
        obj_query = sf.query["select id from " + i] 
        jsondata = json.loads[json.dumps[obj_query['records']]]
        length = len[jsondata]
        i = {}
        k = 0

        for j in range[length]:
            obj_id = jsondata[j]['Id']
            # print["id " + obj_id]

            if k == 0:
                ids = "\"" + obj_id + "\""
                k = 1
            else:
                ids = ids + ",\"" + obj_id + "\""  

        if count != len_obj - 1: 
            file.write[ids]    
        else:
            file.write[ids]    

        count += 1
    file.write["}"]

Đầu ra cuối cùng sẽ giống như:

{
"a":["12","23",...],
"b":["234","456",...],
}

Đây là blog đầu tiên của tôi và chương trình đầu tiên. Hãy hướng dẫn tôi thông qua điều này.

Xin hãy tha thứ cho thụt lề của chương trình vì tôi không thể viết nó ở đây đúng.

Bạn đang ở đây bởi vì khi bạn cố gắng mã hóa/tuần tự mảng numpy thành định dạng JSON, bạn đã nhận được một kiểu mẫu:

lis = ['a','b',...]
2. Trong bài viết này, tôi sẽ chỉ cho bạn cách & nbsp; tạo ra mảng numpy json serializable & nbsp; để bạn có thể chuyển đổi bất kỳ mảng numpy nào thành dữ liệu được định dạng JSON.

Như bạn đã biết mô-đun JSON tích hợp & nbsp; của Python chỉ có thể xử lý các loại nguyên thủy có tương đương JSON trực tiếp [ví dụ: từ điển, danh sách, chuỗi, số, không, v.v.]. Để tuần tự hóa mảng đa chiều thành JSON, chúng ta cần viết một bộ mã hóa JSON tùy chỉnh.write a custom JSON Encoder.

Giải thích cách tuần tự hóa mảng numpy thành json

Bộ mã hóa JSON tùy chỉnh để tuần tự hóa numpy ndarray

Mô -đun Python JSON có lớp

lis = ['a','b',...]
3, chúng tôi có thể mở rộng nó để có được đầu ra tùy chỉnh hơn. tức là, bạn sẽ phải phân lớp jsonencoder để bạn có thể thực hiện tuần tự hóa json numpy tùy chỉnh.

Khi chúng tôi mở rộng lớp jsonencoder, chúng tôi sẽ mở rộng phạm vi mã hóa JSON của nó bằng cách ghi đè phương thức

lis = ['a','b',...]
4 sẽ được sử dụng khi chúng tôi thực thi
lis = ['a','b',...]
5.

Sử dụng

lis = ['a','b',...]
6
lis = ['a','b',...]
7 của phương thức json.dump [] và json.dumps [] để gọi bộ mã hóa JSON tùy chỉnh của chúng tôi, sẽ chuyển đổi mảng numpy thành dữ liệu được định dạng JSON.

Ví dụ:

lis = ['a','b',...]
8:
lis = ['a','b',...]
8

Để tuần tự hóa mảng numpy thành JSON, chúng ta cần chuyển đổi nó thành cấu trúc danh sách bằng hàm

lis = ['a','b',...]
9. Hãy cùng xem bản demo.

Mã hóa và giải mã mảng numpy đến và từ json

Trong ví dụ này, chúng tôi cố gắng tuần tự hóa mảng numpy thành chuỗi JSON.

import json
from json import JSONEncoder
import numpy

class NumpyArrayEncoder[JSONEncoder]:
    def default[self, obj]:
        if isinstance[obj, numpy.ndarray]:
            return obj.tolist[]
        return JSONEncoder.default[self, obj]

numpyArrayOne = numpy.array[[[11, 22, 33], [44, 55, 66], [77, 88, 99]]]

# Serialization
numpyData = {"array": numpyArrayOne}
encodedNumpyData = json.dumps[numpyData, cls=NumpyArrayEncoder]  # use dump[] to write array into file
print["Printing JSON serialized NumPy array"]
print[encodedNumpyData]

# Deserialization
print["Decode JSON serialized NumPy array"]
decodedArrays = json.loads[encodedNumpyData]

finalNumpyArray = numpy.asarray[decodedArrays["array"]]
print["NumPy Array"]
print[finalNumpyArray]

Output::

Printing JSON serialized NumPy array
{"array": [[11, 22, 33], [44, 55, 66], [77, 88, 99]]}

Decode JSON serialized NumPy array
NumPy Array
[[11 22 33]
 [44 55 66]
 [77 88 99]]

Lưu ý: Chúng tôi đã sử dụng

lis = ['a','b','c']
len_obj = len[lis]

with open["Dataset.json", 'w'] as file:
    for i in lis:
        file.write[i]
        obj_query = i + '_query'       
        obj_query = sf.query["select id from " + i] 
        jsondata = json.loads[json.dumps[obj_query['records']]]
        length = len[jsondata]
        i = {}
        k = 0

        for j in range[length]:
            obj_id = jsondata[j]['Id']
            # print["id " + obj_id]

            if k == 0:
                ids = "\"" + obj_id + "\""
                k = 1
            else:
                ids = ids + ",\"" + obj_id + "\""  

        if count != len_obj - 1: 
            file.write[ids]    
        else:
            file.write[ids]    

        count += 1
    file.write["}"]
0 để chuyển đổi dữ liệu thành mảng numpy: We used
lis = ['a','b','c']
len_obj = len[lis]

with open["Dataset.json", 'w'] as file:
    for i in lis:
        file.write[i]
        obj_query = i + '_query'       
        obj_query = sf.query["select id from " + i] 
        jsondata = json.loads[json.dumps[obj_query['records']]]
        length = len[jsondata]
        i = {}
        k = 0

        for j in range[length]:
            obj_id = jsondata[j]['Id']
            # print["id " + obj_id]

            if k == 0:
                ids = "\"" + obj_id + "\""
                k = 1
            else:
                ids = ids + ",\"" + obj_id + "\""  

        if count != len_obj - 1: 
            file.write[ids]    
        else:
            file.write[ids]    

        count += 1
    file.write["}"]
0 to convert data into NumPy array

Mã hóa mảng numpy thành json và ghi nó vào một tệp

Trong hầu hết các kịch bản, chúng ta cần lưu trữ mảng numpy được nối tiếp của JSON vào một tệp để chúng ta có thể sử dụng nó trong các hệ thống khác nhau.

Trong ví dụ này, chúng tôi sẽ làm như sau:

  • Chuyển đổi hai mảng Numpy thành JSON và ghi nó thành tệp JSON
  • Đọc tệp JSON, trong đó chứa mảng numpy nối tiếp của JSON và chuyển đổi nó thành mảng numpy thực tế.
import numpy
from json import JSONEncoder
import json

class NumpyArrayEncoder[JSONEncoder]:
    def default[self, obj]:
        if isinstance[obj, numpy.ndarray]:
            return obj.tolist[]
        return JSONEncoder.default[self, obj]

numpyArrayOne = numpy.array[[[11 ,22, 33], [44, 55, 66], [77, 88, 99]]]
numpyArrayTwo = numpy.array[[[51, 61, 91], [121 ,118, 127]]]

# Serialization
numpyData = {"arrayOne": numpyArrayOne, "arrayTwo": numpyArrayTwo}
print["serialize NumPy array into JSON and write into a file"]
with open["numpyData.json", "w"] as write_file:
    json.dump[numpyData, write_file, cls=NumpyArrayEncoder]
print["Done writing serialized NumPy array into file"]

# Deserialization
print["Started Reading JSON file"]
with open["numpyData.json", "r"] as read_file:
    print["Converting JSON encoded data into Numpy array"]
    decodedArray = json.load[read_file]

    finalNumpyArrayOne = numpy.asarray[decodedArray["arrayOne"]]
    print["NumPy Array One"]
    print[finalNumpyArrayOne]
    finalNumpyArrayTwo = numpy.asarray[decodedArray["arrayTwo"]]
    print["NumPy Array Two"]
    print[finalNumpyArrayTwo]

Output::

serialize NumPy array into JSON and write into a file
Done writing serialized NumPy array into file
Started Reading JSON file
Converting JSON encoded data into Numpy array
NumPy Array One
[[11 22 33]
 [44 55 66]
 [77 88 99]]
NumPy Array Two
[[ 51  61  91]
 [121 118 127]]

JSON Tệp mảng Numpy được nối tiếp

Mã hóa tất cả các loại numpy một cách chính xác thành json

import json
from json import JSONEncoder
import numpy as np

class NumpyArrayEncoder[json.JSONEncoder]:
    def default[self, obj]:
        if isinstance[obj, np.integer]:
            return int[obj]
        elif isinstance[obj, np.floating]:
            return float[obj]
        elif isinstance[obj, np.ndarray]:
            return obj.tolist[]
        else:
            return super[NumpyArrayEncoder, self].default[obj]

# Serialization
numPyData = {"id": 25, "floatSample": np.float32[1.2], "intSample":np.int32[42], "arangeSample": np.arange[12]}
encodedNumpyData = json.dumps[numPyData, cls=NumpyArrayEncoder]  # use dump[] to write array into file
print["Printing JSON serialized NumPy array"]
print[encodedNumpyData]

# Deserialization
print["Decode JSON serialized NumPy array"]
decodedArrays = json.loads[encodedNumpyData]

numPyFloat = np.asarray[decodedArrays["floatSample"]]
print["numPy Float"]
print[numPyFloat]

numPyInt = np.asarray[decodedArrays["intSample"]]
print["numPy Integer"]
print[numPyInt]

numPyArange = np.asarray[decodedArrays["arangeSample"]]
print["numPy arange"]
print[numPyArange]

Output::

Printing JSON serialized NumPy array
{"id": 25, "floatSample": 1.2000000476837158, "intSample": 42, "arangeSample": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]}
Decode JSON serialized NumPy array
numPy Float
1.2000000476837158
numPy Integer
42
numPy arange
[ 0  1  2  3  4  5  6  7  8  9 10 11]

Sử dụng phương thức panads to_json để tuần tự hóa nandarray thành json

Nếu bạn sử dụng gấu trúc để thao tác dữ liệu, bạn có thể sử dụng hàm

lis = ['a','b','c']
len_obj = len[lis]

with open["Dataset.json", 'w'] as file:
    for i in lis:
        file.write[i]
        obj_query = i + '_query'       
        obj_query = sf.query["select id from " + i] 
        jsondata = json.loads[json.dumps[obj_query['records']]]
        length = len[jsondata]
        i = {}
        k = 0

        for j in range[length]:
            obj_id = jsondata[j]['Id']
            # print["id " + obj_id]

            if k == 0:
                ids = "\"" + obj_id + "\""
                k = 1
            else:
                ids = ids + ",\"" + obj_id + "\""  

        if count != len_obj - 1: 
            file.write[ids]    
        else:
            file.write[ids]    

        count += 1
    file.write["}"]
1 trên chuỗi.
lis = ['a','b','c']
len_obj = len[lis]

with open["Dataset.json", 'w'] as file:
    for i in lis:
        file.write[i]
        obj_query = i + '_query'       
        obj_query = sf.query["select id from " + i] 
        jsondata = json.loads[json.dumps[obj_query['records']]]
        length = len[jsondata]
        i = {}
        k = 0

        for j in range[length]:
            obj_id = jsondata[j]['Id']
            # print["id " + obj_id]

            if k == 0:
                ids = "\"" + obj_id + "\""
                k = 1
            else:
                ids = ids + ",\"" + obj_id + "\""  

        if count != len_obj - 1: 
            file.write[ids]    
        else:
            file.write[ids]    

        count += 1
    file.write["}"]
2 Chuyển đổi đối tượng thành chuỗi JSON. Chúng ta có thể vượt qua mảng numpy cho nó để có được đại diện JSON.

lis = ['a','b',...]
0

Output::

lis = ['a','b',...]
1

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ó lẽ tôi đã bỏ lỡ một trong những cách để tuần tự hóa

lis = ['a','b','c']
len_obj = len[lis]

with open["Dataset.json", 'w'] as file:
    for i in lis:
        file.write[i]
        obj_query = i + '_query'       
        obj_query = sf.query["select id from " + i] 
        jsondata = json.loads[json.dumps[obj_query['records']]]
        length = len[jsondata]
        i = {}
        k = 0

        for j in range[length]:
            obj_id = jsondata[j]['Id']
            # print["id " + obj_id]

            if k == 0:
                ids = "\"" + obj_id + "\""
                k = 1
            else:
                ids = ids + ",\"" + obj_id + "\""  

        if count != len_obj - 1: 
            file.write[ids]    
        else:
            file.write[ids]    

        count += 1
    file.write["}"]
3 thành JSON. 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 dưới đây.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.

Làm thế nào để bạn viết một mảng cho một JSON trong Python?

Sau đây là quá trình từng bước để viết JSON vào tệp ...
Chuẩn bị chuỗi JSON bằng cách chuyển đổi một đối tượng Python sang chuỗi JSON bằng JSON. chức năng dumps [] ..
Tạo tệp JSON bằng hàm mở [tên tệp, 'w']. Chúng tôi đang mở tệp ở chế độ ghi ..
Sử dụng tệp. ....
Đóng tệp JSON ..

Làm cách nào để chuyển đổi một mảng thành JSON?

JS mảng cho JSON bằng JSON.const jsonstring = json.Stringify [[1, 2, 3, 4, 5]];JSON.Phương thức Stringify [] chuyển đổi một đối tượng JavaScript, mảng hoặc giá trị thành chuỗi JSON.const jsonString = JSON. stringify[[1, 2, 3, 4, 5]]; The JSON. stringify[] method converts a JavaScript object, array, or value to a JSON string.

Bạn có thể lưu trữ một mảng trong JSON không?

Mảng JSON có thể lưu trữ các giá trị của chuỗi loại, mảng, boolean, số, đối tượng hoặc null.Trong mảng JSON, các giá trị được phân tách bằng dấu phẩy.Các phần tử mảng có thể được truy cập bằng toán tử [].Mảng JSON có các loại khác nhau.. In JSON array, values are separated by commas. Array elements can be accessed using the [] operator. JSON Array is of different types.

Làm cách nào để lưu một mảng numpy dưới dạng json?

Sử dụng CLS kwarg của JSON.kết xuất [] và json.Phương thức Dumps [] để gọi bộ mã hóa JSON tùy chỉnh của chúng tôi, sẽ chuyển đổi mảng numpy thành dữ liệu được định dạng JSON.Để tuần tự hóa mảng numpy thành JSON, chúng ta cần chuyển đổi nó thành cấu trúc danh sách bằng hàm Tolist [].convert it into a list structure using a tolist[] function.

Bài Viết Liên Quan

Chủ Đề