Convert JSON to Array Using `json.The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.
Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
' { } ' used for Object and ' [] ' is used for Array in json.
If you pass the JSON in your post to json_decode
, it will fail. Valid JSON strings have quoted keys:
json_decode('{foo:"bar"}'); // this fails
json_decode('{"foo":"bar"}', true); // returns array("foo" => "bar")
json_decode('{"foo":"bar"}'); // returns an object, not an array.
Try this:
$data = json_decode($your_json_string, TRUE);
the second parameter will make decoded json string into an associative arrays.
If you are getting the JSON string from the form using $_REQUEST
, $_GET
, or $_POST
the you will need to use the function html_entity_decode()
. I didn't realize this until I did a var_dump
of what was in the request vs. what I copied into and echo
statement and noticed the request string was much larger.
Correct Way:
$jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);
With Errors:
$jsonText = $_REQUEST['myJSON'];
$myArray = json_decode($jsonText, true);
echo json_last_error(); //Returns 4 - Syntax error;
Use json_decode($json_string, TRUE)
function to convert the JSON object to an array.
Example:
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$my_array_data = json_decode($json_string, TRUE);
NOTE: The second parameter will convert decoded JSON string into an associative array.
===========
Output:
var_dump($my_array_data);
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
If you are getting json string from URL using file_get_contents
, then follow the steps:
$url = "http://localhost/rest/users"; //The url from where you are getting the contents
$response = (file_get_contents($url)); //Converting in json string
$n = strpos($response, "[");
$response = substr_replace($response,"",0,$n+1);
$response = substr_replace($response, "" , -1,1);
print_r(json_decode($response,true));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With