N
N
Natalia2017-03-27 14:27:48
PHP
Natalia, 2017-03-27 14:27:48

How to set up json_encode?

Data is exported incorrectly to json. The variable stores an array of float numbers. var_dump outputs the following:

2823 => 
    array (size=3)
      'o' => int 3
      'p' => string '58.9' (length=4)
      'b' => float 6.6
  2824 => 
    array (size=3)
      'o' => int 3
      'p' => string '57.1' (length=4)
      'b' => float 6.4

This is true and when exporting to json I expect the same values. But it echo json_encode($var)outputs the following:
"2823":{"o":3,"p":"58.9","b":6.600000000000001},"2824":{"o":3,"p":"57.1","b":6.4}

It can be seen that the element bis not converted correctly in the first case, although it is correct in the second case. These are only 2 elements from the entire array, but in most cases it is converted crookedly.
I understand that if the same line with json is pushed back into json_decode, then everything will be fine, but I print the line with json into a hidden div and then parse with it and get it in a variable
$.parseJSON($('#forang').text())
2823:Object
      b:6.600000000000001
      o:3
      p:"58.9"
2824:Object
      b:6.4
      o:3
      p:"57.1"

-
I also noticed such a moment: if you do it simply , then it turns out right - The essence of the question is why this happens and how to make sure that it is always converted correctly and with as many characters after the comma as there were in the variable. echo json_encode(['a'=>6.6]);{"a":6.6}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly, 2017-03-28
@Skit25

Look at the constants the constants php.net/manual/en/json.constants.php
For example: Guarantees that a float value will be converted exactly to a float value...
Either encode base64 before json, although I think there is a constant that is either as a string all will either pass or tell json_encode to mind your own business.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question