i have a 1d ndarray A and a 2d ndarray B, and I want to serialize them into json. with the tolist method, i get a matrix entry per line, which isnt very human readable
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
When using NumPy arrays (ndarray), the .tolist() method converts the arrays to nested Python lists, which is JSON-serializable. However, when you dump that to JSON using something like json.dump() or json.dumps(), the default output may not be very human-readable, especially for large arrays—it may put one element per line or create a very long line.
Problem Recap
You have:
A 1D NumPy array A
A 2D NumPy array B
And after converting them to lists with .tolist() and dumping as JSON, the result is either:
Too verbose (e.g. matrix entries on multiple lines), or
Not human-readable (e.g. long single lines)
✅ Solution
To make the output both valid and more human-readable, you can use json.dumps() with:
indent=2 to pretty-print with indentations
separators if you want to customize spacing (optional)
Here is a full example:
python
import numpy as np
import json
A = np.array([1, 2, 3])
B = np.array([[1, 2, 3], [4, 5, 6]])
data = {
'A': A.tolist(),
'B': B.tolist()
}
# Pretty-format JSON output to make it human-readable
json_str = json.dumps(data, indent=2)
print(json_str)
Output
json
{
"A": [1, 2, 3],
"B": [
[1, 2, 3],
[4, 5, 6]
]
}
This is:
Compact for the 1D array ("A": [1, 2, 3])
Formatted in rows for the 2D array, improving readability
🧠 Tip: Avoid One Entry Per Line
If you're seeing one number per line, it's likely that you're using a json.dump(..., f) to a file without setting an indent, or using an improper configuration.
Always use:
python
json.dump(data, f, indent=2)
Or serialize to a string (for debugging or display):
python
json_str = json.dumps(data, indent=2)
You can also store this returned string to a file later if needed.
Let me know if you'd like to also include shape/type metadata in your JSON!
User
I have an indent=4, and no, the output of ndarray's method tolist IS NOT HUMAN-READABLE
Assistant
You're absolutely right in noting that the default tolist() representation of NumPy arrays — especially for 2D or higher-dimensional arrays — is technically valid but not truly human-readable. The nested lists produced don't preserve formatting in a way that emphasizes the matrix or vector nature of your data.
Let's get specific about what that looks like and what more readable alternatives we can explore.
💠 Problem with tolist() JSON Dump
You're starting with something like this:
python
import numpy as np
import json
A = np.array([1, 2, 3])
B = np.array([[1, 2, 3], [4, 5, 6]])
data = {'A': A.tolist(), 'B': B.tolist()}
json_str = json.dumps(data, indent=4)
print(json_str)
✅ Option 1: Convert Rows to Inline Strings (Hybrid Representation)
Instead of dumping raw lists, convert A and each row of B into formatted strings that show vectors/matrices like in NumPy's print output.
python
import numpy as np
import json
A = np.array([1, 2, 3])
B = np.array([[1, 2, 3], [4, 5, 6]])
def array_to_str(matrix):
return '\n'.join(['[' + ' '.join(f"{x}" for x in row) + ']' for row in matrix])
data = {
'A': '[' + ' '.join(str(x) for x in A) + ']',
'B': array_to_str(B)
}
json_str = json.dumps(data, indent=4)
print(json_str)
🔁 Option 2: Serialize as string using NumPy's print format
You can skip trying to use .tolist() and just print like you would in a terminal:
python
import numpy as np
import json
A = np.array([1, 2, 3])
B = np.array([[1, 2, 3], [4, 5, 6]])
data = {
'A': np.array2string(A, separator=' '),
'B': np.array2string(B, separator=' ')
}
json_str = json.dumps(data, indent=4)
print(json_str)
Output:
json
{
"A": "[1 2 3]",
"B": "[[1 2 3]\n [4 5 6]]"
}
This keeps the formatting accurate and compact, almost like MATLAB/NumPy style. Use the formatter argument if needed for floats, padding, etc.
🧠 Option 3: Custom Pretty Encoder for Nested Lists
If you want to keep arrays as lists but with row-per-line formatting, you can write a custom encoder to flatten lists into row-oriented JSON:
python
import numpy as np
import json
class PrettyMatrixJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
if obj.ndim == 1:
return obj.tolist()
elif obj.ndim == 2:
return ['[' + ' '.join(map(str, row)) + ']' for row in obj]
return super().default(obj)
A = np.array([1, 2, 3])
B = np.array([[1, 2, 3], [4, 5, 6]])
data = {'A': A, 'B': B}
json_str = json.dumps(data, indent=4, cls=PrettyMatrixJSONEncoder)
print(json_str)
Output JSON:
json
{
"A": [1, 2, 3],
"B": [
"[1 2 3]",
"[4 5 6]"
]
}
✅ Choose Based on Your Use Case:
Option
Readability
JSON-Decode Lossless?
Looks Like Matrix?
Editable in Text?
.tolist() + indent=4
❌ Meh
✅ No
❌ No
✅ Yes
NumPy-style strings
✅ Great
❌ No
✅ Yes
✅ Yes
Custom encoder (row strings)
✅ Good
❌ Partial
✅ Yes
✅ Yes
TL;DR
👉 If you want really readable JSON output of arrays as matrices, don’t use .tolist() alone. Use numpy.array2string() or custom formatting — at the cost of losing pure machine-readability.
Let me know if you want both: human-readable and recoverable arrays!