What I want to do is the following:
<?php
$str='{
"action" : "create",
"record" : {
"type": "$product",
"fields": {
"name": "Bread",
"price": "2.11"
},
"namespaces": { "my.demo": "n" }
}
}';
echo $str;
echo "<br>";
$jsonstr = json_decode($str, true);
print_r($jsonstr);
?>
i think this should Work, its just that the Keys should also be in double quotes if they are not numerals.
your string should be in the following format:
$str = '{"action": "create","record": {"type": "n$product","fields": {"n$name": "Bread","n$price": 2.11},"namespaces": { "my.demo": "n" }}}';
$array = json_decode($str, true);
echo "<pre>";
print_r($array);
Output:
Array
(
[action] => create
[record] => Array
(
[type] => n$product
[fields] => Array
(
[n$name] => Bread
[n$price] => 2.11
)
[namespaces] => Array
(
[my.demo] => n
)
)
)
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.
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 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;
You can change a string to JSON as follows and you can also trim, strip on string if wanted,
$str = '[{"id":1, "value":"Comfort Stretch"}]';
//here is JSON object
$filters = json_decode($str);
foreach($filters as $obj){
$filter_id[] = $obj->id;
}
//here is your array from that JSON
$filter_id;