如何将含数组的Python字典JSON序列化并内联数组写入文件
There are two straightforward approaches to achieve this, depending on whether you want compact JSON or indented (human-readable) JSON with inline arrays.
Approach 1: Compact JSON (No Indentation, All Inline)
If you don’t need hierarchical indentation and just want all content (including arrays) to be in a compact, single-line format, use the separators parameter in json.dump() or json.dumps():
import json # Your dictionary data your_dict = { '#charliehebdo_attack_paris-20150107_072714-20150107_085144': { 'OWA_max': 0.57489770154717, 'features': [0.57489770154717, 0.3087177211515125, 0.30136460335548143, ...], 'truth': 1.0, 'weights': [1, 0, 0, 0, ...] } } # Write to file with compact formatting with open('output_compact.json', 'w', encoding='utf-8') as f: json.dump(your_dict, f, separators=(',', ': '), ensure_ascii=False)
Why this works:
- The
separators=(',', ': ')parameter removes extra whitespace between elements, forcing arrays to stay inline. ensure_ascii=Falsepreserves any non-ASCII characters in your keys/values (safe to use even if you don’t have them).
Approach 2: Indented JSON with Inline Arrays
If you want the dictionary hierarchy to be indented for readability but keep arrays inline, serialize normally first, then post-process the JSON string to collapse array blocks:
import json import re # Your dictionary data your_dict = { '#charliehebdo_attack_paris-20150107_072714-20150107_085144': { 'OWA_max': 0.57489770154717, 'features': [0.57489770154717, 0.3087177211515125, ...], 'truth': 1.0, 'weights': [1, 0, 0, ...] } } # Step 1: Serialize with indentation for readability json_str = json.dumps(your_dict, indent=2, ensure_ascii=False) # Step 2: Collapse arrays into single lines using regex processed_json = re.sub( r'\[\s*(.*?)\s*\]', lambda match: '[' + match.group(1).replace('\n', '').replace(' ', ' ').strip().replace(' ,', ',') + ']', json_str, flags=re.DOTALL ) # Step 3: Write the processed JSON to file with open('output_indented.json', 'w', encoding='utf-8') as f: f.write(processed_json)
Why this works:
json.dumps(..., indent=2)creates a human-readable structure with indented keys.- The regex matches multi-line array blocks, removes newlines and excess whitespace, and collapses them into a single line.
- The lambda function cleans up any leftover spacing issues (like accidental spaces before commas).
Bonus: Custom JSON Encoder (Advanced)
For full control over serialization, you can subclass json.JSONEncoder to handle arrays inline while preserving indentation for dicts. This avoids post-processing and is great for large datasets:
import json class InlineArrayEncoder(json.JSONEncoder): def __init__(self, indent=2, **kwargs): super().__init__(**kwargs) self.indent = indent self.current_indent = 0 def encode(self, obj): if isinstance(obj, list): return '[' + ', '.join(self.encode(item) for item in obj) + ']' elif isinstance(obj, dict): self.current_indent += self.indent indent_str = '\n' + ' ' * self.current_indent items = [ f'{self.encode(k)}:{indent_str}{self.encode(v)}' for k, v in obj.items() ] self.current_indent -= self.indent closing_indent = '\n' + ' ' * self.current_indent if self.current_indent > 0 else '' return '{' + indent_str + ','.join(items) + closing_indent + '}' else: return super().encode(obj) # Usage with open('output_custom.json', 'w', encoding='utf-8') as f: json.dump(your_dict, f, cls=InlineArrayEncoder, ensure_ascii=False)
内容的提问来源于stack exchange,提问作者ocram

