Skip to content

Instantly share code, notes, and snippets.

@hrobeers
Last active November 15, 2015 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrobeers/21a580da01b8110b1bb1 to your computer and use it in GitHub Desktop.
Save hrobeers/21a580da01b8110b1bb1 to your computer and use it in GitHub Desktop.
reduce json floating point precision to reduce size
// reduce json floating point precision to reduce size
#include <iostream>
#include <string>
#include <regex>
#include <vector>
const std::string foil = "{\"foil\":{\"history\":[],\"layerCount\":6,\"outline\":{\"area\":0.0094394211977858536,\"height\":0.10000000000000001,\"path\":[[\"M\",0,0],[\"C\",-0.8090161000000009,-1.065339999999992,146.79888589999996,-14.155744000000027,159.50071800000001,-92.968964000000028],[\"C\",328.158458,-105.34453400000007,441.98747800000001,-231.89464399999997,445.60909800000002,-144.481404],[\"C\",340.96483799999999,-107.30037800000002,411.20925799999998,-72.230819999999994,411.10157800000002,-73.084100000000007],[\"C\",173.75719790000005,-73.240800000000007,353.8799179999998,-1,353.87991799999986,0]],\"sweep\":0.96055560932291262,\"uuid\":\"{76d2a5ae-8d14-4617-8b6a-122401df6f20}\"},\"profile\":{\"botProfile\":[[\"M\",0,0],[\"C\",0,0,-26,69,114,34],[\"C\",91,9,300,0,300,0]],\"symmetry\":\"Asymmetric\",\"thickness\":0.01,\"thicknessRatio\":1.0249374147947978,\"topProfile\":[[\"M\",0,0],[\"C\",0,0,56,-45,146,-45],[\"C\",130,-6,300,0,300,0]],\"uuid\":\"{312fbfeb-0a7d-4a3c-8c1f-ed0482ca3324}\"},\"thickness\":{\"topProfile\":[[\"M\",0,-30],[\"C\",3,-29,193.99999999999994,-32,312.99999999999994,0]],\"uuid\":\"{ce15346c-9a80-4b89-b692-2783f161b1ec}\"},\"uuid\":\"{9cf11cd5-e858-407e-bd16-e402da204d42}\"}}";
std::string reduce_precision(const std::string &json)
{
std::string retVal;
std::regex re_float("[-]*\\d+[.]\\d+");
std::regex re_zeros("[0]{6,}\\d");
std::regex re_nines("[9]{6,}\\d");
std::sregex_iterator next(json.begin(), json.end(), re_float);
std::sregex_iterator end;
size_t prev_end = 0;
while (next != end) {
std::smatch match = *next;
// append the non-float part
retVal.append(json.substr(prev_end, match.position() - prev_end));
// reduce float precision and append
retVal.append(std::regex_replace(std::regex_replace(match.str(), re_zeros, ""), re_nines, "9"));
prev_end = match.position() + match.length();
next++;
}
// append the last part
retVal.append(json.substr(prev_end));
return retVal;
}
int main()
{
std::string foil_reduced = reduce_precision(foil);
std::cout << foil_reduced << std::endl;
std::cout << "foil length: " << foil.length() << std::endl;
std::cout << "foil_reduced length: " << foil_reduced.length() << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment