decode array with multiple json response in one api response in php - php

I have a JSON output in my API response,
Like this:-
{ "m_time" : "2015-04-07 11:37:35", "id" : "30", "msg" : "Hai there 1"}
{ "m_time" : "2015-04-07 11:37:36", "id" : "31", "msg" : "Hai there 2"}
{ "m_time" : "2015-04-07 11:37:37", "id" : "32", "msg" : "Hai there 3"}
I have tried with JSON decode but it returns "null" &
I can't substr from response because it doesn't have any "," like this to separate each response (and not possible to change anything from API response)
How can I access each response from the data??

Since JSON itself is not "streamable" (you can't add data on the end of a valid JSON document and still have a valid JSON document), there is a common format sometimes called "JSON lines": each line of data is a separate JSON document.
To process that data, all you need to do is split the string on newlines (e.g. using explode), then use a foreach loop to pass each line in turn to json_decode.

Related

How to change value of special key in json using php?

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

extracting json in php

From MySQL row, I have this json formatted data:
$row['details'] =
{
"previous_employer":[
{"employer":"string1","address":"address1"},
{"employer":"string2","address":"address2"},
{"employer":"string3","address":"address3"}],
"profile":[
"firstname":"John",
"lastname":"Adams",
"gender":"male",
"age":"35",
"contact":"123456789"]
}
I want to extract employer and address on the previous_employer array of objects,
but when I do this:
$json = json_decode($row['details'],true); //decode into array
foreach($json['previous_employer'] as $d){
echo "employer:".$d['employer']."<br>address:". $d['address']."<br>";
}
it gives me an error of
Warning: Invalid argument supplied for foreach()
How can I fix this? Pls advise.. thanks!
You JSON is invalid, "profile" must be
An Object:
"profile": {
"firstname": "John",
"lastname": "Adams",
"gender": "male",
"age": "35",
"contact": "123456789"
}
or an Array of Object (here his length == 1)
"profile": [{
"John",
"Adams",
"male",
"35",
"123456789"
}]
or a Simple Array (not associative array/map)
"profile": [
"John",
"Adams",
"male",
"35",
"123456789"
]
Now, your posted code will work as a charm without any modifications ... :)
json_decode() does not necessarily succeed (just imagine you feed it with complete garbage, why should it return something?). You need to do the following error checking:
Verify its return value:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
If valid data can be expected to return null some times, call json_last_error() and check whether it's JSON_ERROR_NONE.
Last but not least, you can explore any variable with var_dump(). You don't need to make assumptions about its content.

Is my JSON an array or an object?

1[[23[]]
I understand that '[' denotes a JOSNArray and '{' denotes a JSONObject. However as my result starts with [ is the entire data piece now an array even if { comes before the actual string?
And if parsing in android, should I be parsing for array or object?
My PHP script:
It's an array contsining single object. The string delimits name of the first item of the first object.
As stated by Zbynek Vyskovsky its an array with single object so to get the data you can use
JSONArray jsonArray=new JSONArray(<your json object>);
JSONObject jsonObject = jsonArray.get(0);
String date = jsonObject.getString("Date");
String temp = jsonObject.getString("Temp");
The best way to determine this is format first .
paste your response in this site http://json.parser.online.fr/
there you will see
1)red square brackets -represent an array.
2)blue curly brackets represents an object.
in short you have an array containing single object.
Your Json is an array which contains only one Json object.I will show actually how it works with JSon Array and JsonObject.
For example I have a JSON Array :
[{
"name": "abc",
"description": "ABC server",
"state": "online"
},
{
"name": "xyz",
"description": "XYZ client",
"state": "online"
},
{
"name": "mnp",
"description": "MNP server",
"state": "online"
}]
So The above array actually contains 3 Json objects like [{Obj1},{Obj2},{Obj3}].
When we try to get any of the value for a key then first we need to store the JSon Array and then after we need to get the exact Json object by passing index e.g: jsonObject obj = JsonArray.get(0).
Soon after you pass the key to the Json object in get() method, you will get your key. e.g: String s = obj.get("state").

PHP - Extracting an array (object?) from a JSON file

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);

json_decode (file_get_contents) returns null

Im trying to create a json object from my POST data. When i var_dump the $postData i get the folowing result:
string(92) "{
"name" : "bier",
"city" : "Rotterdam"
"address": "straat 41"
"max_persons": "150"
}"
When i var_dump $json i get NULL
this is my code:
$postData = file_get_contents("php://input");
$json = json_decode($postData);
var_dump($postData);
This is what i am sending to my webservice:
{
"name" : "bier",
"city" : "Rotterdam"
"address": "straat 41"
"max_persons": "150"
}
Why is Json_decode returning NULL?
From the documentation:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
Now see JSON Lint:
Parse error on line 3:
... "city": "Rotterdam""address": "straat 4
-----------------------^
Expecting '}', ':', ',', ']'
The JSON is invalid. There is a comma missing between "Rotterdam" and "address"
You are missing a comma in your json, after "straat 41".
{ "name" : "bier", "city" : "Rotterdam" "address": "straat 41", "max_persons": "150" }
Use jsonlint.com to validate the json you are trying to decode.

Categories