Forked from AlienHoboken/valve-data-format-jsonify.php
Created
February 22, 2018 20:51
-
-
Save iFeelPixel/ca5ea84e946cf15f4c2d49a47228e872 to your computer and use it in GitHub Desktop.
This short PHP script will create valid JSON data from Valve Data Format (VDF) data, such as items_game.txt files for TF2 and DotA 2. This allows for much greater ease in parsing the data it contains.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//load VDF data either from API call or fetching from file/url | |
//no matter your method, $json must contain the VDF data to be parsed | |
$json = file_get_contents("items_game.txt"); | |
//encapsulate in braces | |
$json = "{\n$json\n}"; | |
//replace open braces | |
$pattern = '/"([^"]*)"(\s*){/'; | |
$replace = '"${1}": {'; | |
$json = preg_replace($pattern, $replace, $json); | |
//replace values | |
$pattern = '/"([^"]*)"\s*"([^"]*)"/'; | |
$replace = '"${1}": "${2}",'; | |
$json = preg_replace($pattern, $replace, $json); | |
//remove trailing commas | |
$pattern = '/,(\s*[}\]])/'; | |
$replace = '${1}'; | |
$json = preg_replace($pattern, $replace, $json); | |
//add commas | |
$pattern = '/([}\]])(\s*)("[^"]*":\s*)?([{\[])/'; | |
$replace = '${1},${2}${3}${4}'; | |
$json = preg_replace($pattern, $replace, $json); | |
//object as value | |
$pattern = '/}(\s*"[^"]*":)/'; | |
$replace = '},${1}'; | |
$json = preg_replace($pattern, $replace, $json); | |
//we now have valid json which we can use and/or store it for later use | |
file_put_contents("items_game.json", $json); | |
/* NB: this does not allow for creation of json arrays, however. | |
* if you wish to keep working with the json data in PHP, you could | |
* do something like this to get an array where needed. eg. for items | |
*/ | |
$data->items_game->items = get_object_vars($data->items_game->items); //items object is now an array | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment