It's stored inside MongoDB and passed to my view file with json_decode.
Using PHP, how can I grab the values from within?
"environment" : {
"_id" : "QU",
"name" : "QA Unstable",
"streams" : "unstable",
"hosts" : [
"deployclient1",
"deployclient2"
]
}
Use $array = json_decode($json_string, TRUE);. Second variable makes it array if you supply TRUE or object if you omit it.
Now to actually answer the question since you already know of json_decode:
Using PHP, how can I grab the values from within?
json_decode will evaluate the JSON string into a object in PHP (by default) which means you can use basic dynamic accession syntax to get to your values, i.e. to get _id:
$object->environment->_id;
Or a host:
$object->environment->hosts[0]
That will return: deployclient1
Don't forget to wrap the string in curly braces...
$str = '{"environment" : {
"_id" : "QU",
"name" : "QA Unstable",
"streams" : "unstable",
"hosts" : [
"deployclient1",
"deployclient2"
]
}}';
print_r(json_decode($str, true));
Related
I have below json data and decode it to display on the screen. When I check the type of the value, it shows array instead of object. How to get actual type of value in PHP.
JSON is
{ "allData" : { "image" : [], "contents": {.., "box": {}, "text":[]} } }
When I decode and parse the above JSON data the "allData", "contents", "box" type are shows as array instead of object. How can I get those type as object and "image" type as array. Please help.
Thanks,
Guru
This normally occurs when you are using the true option in the json_decode function.
For eg.,
$str = '{"allData":{"image":["img1.png"],"contents":{"title":"title name","box":{"name":["sample text 1","sample text2"]},"text":[]}}}';
var_dump(json_decode($str, true));
Just try to remove the true in the json_decode function and you should get an object.
Hope this helps.
If you use json_decode with the true option, it will return the result as an array.
Maybe you can check this link.
If you get "Cannot use object of type stdClass as array" the error, you can look at this answer.
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
Extract from the RFC 7159 (JSON) :
These are the six structural characters:
begin-array = ws %x5B ws ; [ left square bracket
begin-object = ws %x7B ws ; { left curly bracket
end-array = ws %x5D ws ; ] right square bracket
end-object = ws %x7D ws ; } right curly bracket
..
However: php allows you to treat the result as an array (of arrays)
so:
json_decode($json, true); // return as array
returns the result as an array.
and
json_decode($json)
gives you the result as Objects AND arrays . So given your example:
"allData" : { "image" : [], ..
returns a stdClass-Object with the field "image" of type array. The array is empty for your example.
So to retrieve all images, use something like:
$result=json_decode($json);
foreach($result->allData->image as $img) {
echo "found image: $img.";
}
I'm inserting value with implode and get this type json
[
{
"id":"1",
"f_name":"Mitrajit",
"l_name":"Samanta",
"class":"XII",
"section":"A,B,C",
"roll":"1",
"status":"1"
}
]
but I want this type :-
[
{
"f_name" : "Mitrajit",
"l_name" : "Samanta",
"class" : "XII",
"section": ["A","B","C"],
"roll" : "1",
"status" : "1"
}
]
how can I get "A,B,C" to ["A","B","C"]?
You need to use json_decode() to converting json to php array. Then select section value in json array and use explode() to converting it to array. At the end convert php array to json using json_encode()
$json = json_decode($jsonStr, true);
$json[0]["section"] = explode(",", $json[0]["section"]);
$jsonStr = json_encode($json);
Check result in demo
I've got a JSON file and I want to access the contents via PHP. The problem is accessing an array inside the JSON file. Other methods suggested on this site don't seem to work. An example of the JSON structure is at the bottom. The PHP code here is the only PHP code between my opening and closing PHP tags.
This PHP code works. I'm accessing something that isn't an array.
$jsondata = file_get_contents('BFZ.json');
$data = json_decode($jsondata, true);
$id = $data['name'];
echo $id;
This doesn't work. I'm trying to access the "name" portion of the "cards" array (object?) in the JSON file.
$jsondata = file_get_contents('BFZ.json');
$data = json_decode($jsondata, true);
$id = $data['cards']['name'];
echo $id;
This also doesn't work:
$id = $data['cards']['name'][0];
The structure of the JSON file with example info:
"name" : "Nemesis",
"code" : "NMS",
"gathererCode" : "NE",
"oldCode" : "NEM",
"magicCardsInfoCode" : "ne",
"releaseDate" : "2000-02-14",
"border" : "black",
"type" : "expansion",
"block" : "Masques",
"onlineOnly" : false,
"booster" : [ "rare", ... ],
"cards" : [ {}, {}, {}, ... ]
The structure of the "cards" array (object?) of the JSON file with example info:
"name" : "Sen Triplets",
"manaCost" : "{2}{W}{U}{B}",
"cmc" : 5,
"colors" : ["White", "Blue", "Black"],
"type" : "Legendary Artifact Creature — Human Wizard",
"supertypes" : ["Legendary"],
"types" : ["Artifact", "Creature"],
"subtypes" : ["Human", "Wizard"],
"rarity" : "Mythic Rare",
"text" : "At the beginning of your upkeep, choose target opponent.
This turn, that player can't cast spells or activate
abilities and plays with his or her hand revealed.
You may play cards from that player's hand this turn.",
"flavor" : "They are the masters of your mind.",
"artist" : "Greg Staples",
"number" : "109",
"power" : "3",
"toughness" : "3",
"layout" : "normal",
"multiverseid" : 180607,
"imageName" : "sen triplets",
"id" : "3129aee7f26a4282ce131db7d417b1bc3338c4d4"
I got the JSON file from here: http://mtgjson.com/ . The file references the card game Magic: the Gathering. I'm using PHP because my intention is to eventually load the data into a MySQL database.
It looks like cards key holds an array of json objects. json_decode() will parse it as such.
Given that, $data['cards'][0]['name'] should give you the name of first card. Analogically, $data['cards'][1]['name'] should give you name of the second card.
The $data['name'] you were targeting was the one from the extension.
You need to access the array ['cards'] to reach the card list then with a loop you can get all the cards name.
you might want to do that :
$jsondata = file_get_contents('http://mtgjson.com/json/BFZ.json');
$data = json_decode($jsondata, true);
$cards = $data['cards'];
$cardsName = array();
foreach ($cards as $card) {
$cardsName[] = $card['name'];
}
var_dump($cardsName);
This will create an array will all the cards name
You need to unserialize your data
$jsondata = file_get_contents('http://mtgjson.com/json/BFZ.json');
$data = unserialize($jsondata);
// Show the unserialized data;
var_dump ($data);
I'm trying to read a json file and parse it to an array, and then acces that array.
This is my JSON file:
{
"stijn",
"bert",
"tom"
}
This is how I try to acces it and convert it to an array:
$string = file_get_contents(__DIR__."/first.json");
$array = json_decode($string, true);
if I do a var_dump of $array I get "null", if I do it of $string I get the contents of the JSON file.
I think that my JSON file is not properly formatted, but if I search for some examples they are not suitable for my list of names.
you are right, your json is not formatted properly. you need to show that it is an array, so like this:
{
names: [
"stijn",
"bert",
"tom"
]
}
OR
[
"stijn",
"bert",
"tom"
]
notice that square brackets are used for an array. if you use the curly braces, it's looking for a key/value pair
What about ?
[
"stijn",
"bert",
"tom"
]
When I do json_encode from this array:
array('aps' => array(
'alert' => array(
'param1'=>array('string'),
'param2'=>'string' )));
I'm getting this JSON object:
{
"aps" : {
"alert" : {
"param1" : {
"0" : "string"
},
"param2" : "string"
}
}
}
Instead of
{
"aps" : {
"alert" : {
"param1" :
["string"],
"param2" : "string"
}
}
}
It seems to work right when the param1 array is not a single item.
How could I fix it? The Json is created from a third party bundle, so I should format the array in PHP so that I could get the correct JSON on json_encode (param1 as a list).
See this answer: https://stackoverflow.com/a/11722121/1466341
And more info here: http://www.php.net/manual/en/function.json-encode.php
Note: When encoding an array, if the keys are not a continuous numeric
sequence starting from 0, all keys are encoded as strings, and
specified explicitly for each key-value pair.
In your case everything should work fine, but I guess you have simplified your PHP array in this example. So, idea is simple - if your PHP array don't have all keys sequential, then json_encode will treat them as keys of object.