Reputation: 402
I have a rather big json file with coordinates in the following format
"[[3.2,1],[4.8,2]]"
which represents (3.2,1) and (4.8,2)
I'm using these coördinates to generate a D3 geographic map, but when php is modelling this information into a geoJSONobject I encounter the following error:
I need to transform the coordinates into a array for which I use json_decode
. However:
json_decode("[[3.2,1],[4.8,2]]")
returns
Array
(
[0] => Array
(
[0] => 3
[1] => 1
)
[1] => Array
(
[0] => 4
[1] => 2
)
)
Where I lose the decimals. How can I prevent this?
{"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": "[[[8.7, 11], [8.89, 12.13],[9.27, 12.13], [9.9, 12], [9.7, 10.8], [8.7, 11]]]"
},
"properties": {
"name": "04",
"count": "25"
}
}]
}
This is an example of the data I'm getting as output. (It is supposed to represent a map of rooms which are get a density color by its usage)
I am able to parse this using jQuery.parseJSON(data)
, but running the following D3 code generates the weirdest errors:
val(svgname).append("g")
.selectAll("path")
.data(geoJSONobject.features)
.enter().append("path")
.attr("d", path)
...
I think it's because of the quotes around the array of coordinates.
The solution I accepted was a workaround, but the true issue was localized php-settings. using:
echo json_encode($dataset, JSON_NUMERIC_CHECK);
in the php-file, all the issues were resolved. Though I'd update the question since it is still being looked at (if anyone would encouter the issue)
Upvotes: 9
Views: 5541
Reputation: 14469
Just wrap the values in quotes: json_decode('[["3.2","1"],["4.8","2"]]');
Upvotes: 0
Reputation: 8168
I had the same problem. I solved it using the followin regex
SOLUTION 1
$yourJsonVariable = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $yourJsonVariable);
Convert it into array
$array = json_decode($yourJsonVariable, true);
Credits goes to this SO LINK
SOLUTION 2
You can set ini_set('precision',1);
SOLUTION 3
$decoded = json_decode($encoded, true, null, JSON_BIGINT_AS_STRING);
NOTE: The Last solution will work only for PHP > 5.4
You might want to take a look at this Blog
Upvotes: 9