PHP项目中未知数据类型识别及JSON转换需求咨询
Hey there! That string you're working with is a PHP serialized array—it's what PHP uses to turn complex data (like arrays or objects) into a string that can be stored or transferred easily. Let's walk through how to convert it to clean JSON format.
First, Let's Understand the Serialized Structure
Your data looks like this:
a:10:{i:1;s:2:"49";i:2;s:2:"53";i:3;s:3:"140";i:4;s:2:"53";i:5;s:2:"53";i:6;s:2:"40";i:7;s:2:"40";i:8;s:2:"60";i:9;s:2:"40";i:10;s:0:"";}
Here's what each part means:
a:10: This is an array with 10 elementsi:1: The first element's key is the integer 1s:2:"49": The value for key 1 is a string (s) with length 2, content "49"- This pattern repeats for all 10 elements
Method 1: Use PHP's Built-in Functions (Most Reliable)
PHP has native functions to handle this perfectly. Just run this code snippet:
// Your serialized string $serialized = 'a:10:{i:1;s:2:"49";i:2;s:2:"53";i:3;s:3:"140";i:4;s:2:"53";i:5;s:2:"53";i:6;s:2:"40";i:7;s:2:"40";i:8;s:2:"60";i:9;s:2:"40";i:10;s:0:"";}'; // Convert serialized string back to a PHP array $array = unserialize($serialized); // Convert the array to formatted JSON $json = json_encode($array, JSON_PRETTY_PRINT); // Output the result echo $json;
The Resulting JSON
When you run the code above, you'll get this nicely formatted JSON:
{ "1": "49", "2": "53", "3": "140", "4": "53", "5": "53", "6": "40", "7": "40", "8": "60", "9": "40", "10": "" }
Method 2: Manual Parsing (If You Don't Have PHP Access)
If you can't run PHP code, you can parse it manually:
- Remove the outer wrapper:
a:10:{and} - Split the remaining string by
;(ignore the last empty item) - Pair up each key (
i:N) with its value (s:L:"content") - Map each pair to a JSON key-value pair, making sure to quote keys and values properly
Note: Manual parsing works for simple arrays like this, but if your serialized data includes objects or nested arrays, stick with PHP's unserialize() to avoid errors.
内容的提问来源于stack exchange,提问作者Mustafa Demirtaş

