iOS Swift中多语言Localizable.string转指定JSON及排序方法
Perfect, let's tackle this step by step—first getting your .strings files into that target JSON structure, then fixing the key ordering mess you're seeing. I'll cover both a flexible Python script approach (great for full control) and a quick command-line fix if you already have the unordered JSON.
1. Convert .strings to Structured JSON (with built-in sorting)
If you haven't nailed the conversion yet, this Python script will handle both parsing your localization files and outputting sorted JSON in exactly the format you want. It even accounts for common .strings quirks like comments and escaped quotes.
First, make sure your files follow the standard iOS project structure:
en.lproj/Localizable.stringsde.lproj/Localizable.stringsfr.lproj/Localizable.strings
Then save this as convert_localizations.py:
import json import re def parse_strings_file(file_path): key_value_pairs = {} # Use 'utf-8' instead of 'utf-16' if your strings files use UTF-8 encoding with open(file_path, 'r', encoding='utf-16') as f: for line in f.readlines(): stripped_line = line.strip() # Skip comments, empty lines, and block comment boundaries if not stripped_line or stripped_line.startswith('//') or stripped_line in ('/*', '*/'): continue # Match the standard key-value pattern: "key" = "value"; match = re.match(r'^"(.+?)"\s*=\s*"(.+?)";$', stripped_line) if match: key = match.group(1) value = match.group(2).replace('\\"', '"') # Unescape quotes key_value_pairs[key] = value return key_value_pairs # Load all three localization files en_localizations = parse_strings_file('en.lproj/Localizable.strings') de_localizations = parse_strings_file('de.lproj/Localizable.strings') fr_localizations = parse_strings_file('fr.lproj/Localizable.strings') # Combine into the target structure, with sorted keys final_json = {} # Get all unique keys across all files, sorted alphabetically all_sorted_keys = sorted(set(en_localizations.keys()).union(de_localizations.keys()).union(fr_localizations.keys())) for key in all_sorted_keys: # Force inner language keys to stay in en → de → fr order final_json[key] = { 'en': en_localizations.get(key, ''), 'de': de_localizations.get(key, ''), 'fr': fr_localizations.get(key, '') } # Write the sorted JSON to file with open('localization.json', 'w', encoding='utf-8') as output_file: json.dump(final_json, output_file, indent=2, sort_keys=True, ensure_ascii=False)
How this works:
- The
parse_strings_filefunction cleans up and parses each .strings file, ignoring comments and handling escaped quotes in values. - We collect all unique keys from your three files and sort them alphabetically for the outer layer.
- For each key, we explicitly define the inner language keys in
en,de,frorder—so they never get jumbled. - The final JSON is written with
sort_keys=Trueto lock in the outer key order, andensure_ascii=Falsekeeps special characters (like German umlauts) intact.
2. Fix Ordering in an Existing JSON File
If you already have the JSON but need to sort the keys, you can use either Python or the jq command-line tool (a staple for quick JSON manipulations).
Option A: Python one-liner
Run this in your terminal (replace input.json and output.json with your file paths):
import json; d=json.load(open('input.json')); json.dump({k:{'en':v['en'],'de':v['de'],'fr':v['fr']} for k in sorted(d.keys())}, open('output.json','w'), indent=2, ensure_ascii=False)
Option B: jq command-line tool
If you have jq installed, run this:
jq --sort-keys '. | map_values(. | {en, de, fr})' input.json > sorted_output.json
This sorts the outer keys alphabetically and forces the inner language keys to stay in en → de → fr order.
Quick Notes:
- If some keys are missing from a language file, the script fills them with an empty string—you can change that to something like
keyor"N/A"by modifying the.get(key, '')part. - Double-check the encoding of your .strings files: iOS defaults to UTF-16, but if you saved them as UTF-8, update the
encodingparameter in theopencalls.
内容的提问来源于stack exchange,提问作者iOSDev2013

