如何高效将大体积自定义格式数据转换为JSON以适配React.js项目?
First off, it’s no surprise your VS Code regex attempt crashed—regex is really not built for handling nested structures like these, especially with 6000 lines of complex data. The nested curly braces, varying string formats, and sheer volume make regex slow, error-prone, and likely to choke even powerful editors. Writing a small script is definitely the way to go here, and there are reliable, efficient alternatives to regex that will handle this properly.
Recommended Approach: Use Python to Parse Lua Tables Directly
Your input data looks almost exactly like Lua table syntax. Instead of trying to regex every edge case, we can leverage a Lua parser in Python to convert the data into a Python dictionary, then dump that straight to JSON. This handles nested structures, trailing commas, and special string characters automatically.
Step 1: Set Up Dependencies
First, install the lupa library, which lets Python execute and interact with Lua code:
pip install lupa
Step 2: Write the Conversion Script
Create a Python file (e.g., convert_to_json.py) with this code:
import lupa import json def convert_lua_table(obj): """Convert Lua-style tables to Python lists/dicts for proper JSON output.""" if isinstance(obj, dict): # Check if the table is a list-like (integer keys starting at 1) keys = sorted(obj.keys()) if all(isinstance(k, int) for k in keys) and keys == list(range(1, len(keys)+1)): return [convert_lua_table(obj[k]) for k in keys] # Convert keys to strings (since JSON doesn't allow integer keys for objects) return {str(k): convert_lua_table(v) for k, v in obj.items()} else: return obj # Initialize Lua runtime lua = lupa.LuaRuntime() # Read your input data file (replace 'items_data.txt' with your actual file path) with open('items_data.txt', 'r', encoding='utf-8') as input_file: raw_data = input_file.read() # Wrap the raw data in a Lua table definition to make it valid Lua code lua_code = f"return {{ {raw_data} }}" # Execute the Lua code to get a Python dict parsed_data = lua.eval(lua_code) # Convert Lua-style tables to JSON-friendly structures cleaned_data = convert_lua_table(parsed_data) # Write the result to a JSON file with open('items.json', 'w', encoding='utf-8') as output_file: json.dump(cleaned_data, output_file, indent=2, ensure_ascii=False)
Step 3: Run the Script
Put all your 6000 lines of data into a text file (e.g., items_data.txt), then run the script:
python convert_to_json.py
This will generate a properly formatted items.json file that you can directly import into your React project.
Why This Works Better Than Regex
- Handles Nested Structures: Unlike regex, the Lua parser understands the hierarchy of your data, so nested objects/lists are converted correctly without breaking.
- Performance: Parsing 6000 lines with this method is fast and won’t crash your editor—Python is built for handling large text files efficiently.
- Edge Case Resilience: It automatically handles trailing commas, special characters in strings (like
{{...}}or[[...]]), and list-like tables (e.g.,{"Distributed"}becomes["Distributed"]in JSON).
Alternative: Manual Syntax Fixes (Not Recommended)
If you absolutely can’t use a script, you could try regex to fix the syntax to valid JSON, but it’s risky. For example:
- Replace
['key'] =with"key": - Replace
{ ["key"] =with{ "key": - Remove trailing commas after last items in objects/lists
- Convert
true/falseto lowercase (JSON uses lowercase)
But even with these, you’ll likely hit edge cases (like strings containing brackets) that break the regex, and processing 6k lines will still be slow. The script approach is far more reliable.
内容的提问来源于stack exchange,提问作者lino_dev

