Convert json string to array in php - arrays

Im using curl the retrieve a json string from a log file. I was able to retrieve the string but it comes in this format.
[{"candy":"lollipop","timestamp":1385504260,"color":"red"}]
[{"candy":"laffytaffy","timestamp":1385504260,"color":"blue"}]
When i try to convert it to an array using decode, its as if decode isn't working. I was hoping someone could assist me in figuring this out.

First, this json seems to be wrong. It should has this format.
[{"candy":"lollipop","timestamp":1385504260,"color":"red"},
{"candy":"laffytaffy","timestamp":1385504260,"color":"blue"}]
Maybe it's the problem.

#Carlos is right your JSON is invalid. You have 2 separate arrays instead of an array of objects.
It should look like this instead:
[
{
"candy": "lollipop",
"timestamp": 1385504260,
"color": "red"
},
{
"candy": "laffytaffy",
"timestamp": 1385504260,
"color": "blue"
}
]
Try like this
<?php
$jsonData = '[{"candy":"lollipop","timestamp":1385504260,"color":"red"},
{"candy":"laffytaffy","timestamp":1385504260,"color":"blue"}]';
$decodedJson = array();
$decodedJson = json_decode($jsonData);
print_r ($decodedJson);
?>

Related

FCM Field "data" must be a JSON array

Hi im working with postman to make my json object FCM message:
But when i try to send:
{
"to":"fzvihT7dFUI:APA91bFVhnWAxXVjlWiiHIs9ZUyL1DE2hZO6GpItJtReh3hcKF1kD6mLuQq9fNP9xvS5bOFWUOG-OW-uyOedc1C43m8jfvD4OOfsBYuMbM7t1-dZEy2kQcuv3gJw6dhneVus2AR_hQHQ",
"data":[
{
"time":1501385514224,
"CC":"1030626890"
}
],
"notification":{
"body":"SPO2:95 \nPulso:75",
"title":"El paciente Daniel Ortiz nesecita asistencia"
}
}
The response its:
Field "data" must be a JSON array:
[{"CC":"1030626890","time":1501385514224}]
But i know the [{"CC":"1030626890","time":1501385514224}] its a array, i dont understand the problem.
What i made wrong?
From the Firebase Cloud Messaging documentation, it seems like data should be a JSON object:
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
},
}
I'm not sure why the error message talks says it needs to be an array. It's like meant as an "associative array" which is really just another term for a JSON object.
I might be too late but for those who still face this problem , following change saved me.
By adding JSON_FORCE_OBJECT to json_encode() it will add missing braces so it should be something like this:
json_encode($fields ,JSON_FORCE_OBJECT));
That's it.
In case you serialize sql/api results data that each item of the array has a numeric key using php, for example an array like:
$results = [
['name'=>'john', 'durname'=>'doe'],
['chuck'=>'john', 'durname'=>'Norris'],
]
Before turning into FCM data try:
$results = [
["time":1501385514224, "CC":"1030626890"]
["time":1501385514334, "CC":"1030126890"]
]
$fcmData = [
"to"=>"fzvihT7dFUI:APA91bFVhnWAxXVjlWiiHIs9ZUyL1DE2hZO6GpItJtReh3hcKF1kD6mLuQq9fNP9xvS5bOFWUOG-OW-uyOedc1C43m8jfvD4OOfsBYuMbM7t1-dZEy2kQcuv3gJw6dhneVus2AR_hQHQ",
"data":[
"data" => $results
],
"notification" => [
"body"=>"SPO2:95 \nPulso:75",
"title"=>"El paciente Daniel Ortiz nesecita asistencia"
]
]
$fcmData = json_encode($fcmData);
// Send push notification here
In case you are using laravel with brozot/laravel-fcm, a good approach is this one.
Thje bottom line is that fcm/push notification data MUST be an associative array.

How to create a JSON array as string from groovy objects?

I have some data in Groovy's objects which I need to convert to a JSON string array. The final result should be..
[
{
"keys":{
"passcode": "12345"
},
"values":{
"EmailAddress": "john#doe.com",
"message": "Hello, is it me you are looking for?"
}
}
]
I found this post but the accepted answer which uses JSON Builder didn't make sense and the second answer using JSON converter didn't work...
def deJson = [
keys: [
passcode: secretCode
],
values: [
EmailAddress:emailData.to[0],
message: content.message
]
] as grails.converters.JSON
This created a JSON object when I needed an array.
Can anyone suggest how I can use JSON Builder or JSON converter to create an array string like I have above?
JSON is specific to Grails (as mentioned in one of the comments in the answer from the previous post). You should have followed the question itself in the post, that has the answer.
Using groovy.json.JsonBuilder, the expected way to serialize would be:
def jsonObj = [
keys: [
passcode: secretCode
],
values: [
EmailAddress:emailData.to[0],
message: content.message
]
]
// In order to get a json array, use a list containing the object
new JsonBuilder([jsonObj]).toPrettyString()

Get each JSON array value using PHP

I've been trying to read this JSON with PHP:
{
"total_found":"49",
"1":{
"title":"Maze Runner-The Scorch Trials 2015 HD-TS x264-Garmin",
"category":"video",
"seeds":2141,
"leechs":1176,
"torrent_size":1122230176,
"torrent_hash":"29d3e7062825a62abdd877ee96dc3fea41183836"
},
"2":{
"title":"Maze.Runner-The.Scorch.Trials.2015.720P.HD-TS.x264.AC3.HQ.Hive-CM8",
"category":"hdrip",
"seeds":395,
"leechs":1856,
"torrent_size":3999751475,
"torrent_hash":"e1e14a5ccf540a739907db2e1e0d810ecdb8bebc"
}
}
How can I get each title and torrent_size?
The easiest thing to do is to decode the JSON to an array. PHP has a built-in function for this:
$results = json_decode($json_data);
http://php.net/manual/en/function.json-decode.php
To clearly see the array structure, try dumping the variable $results using print_r();, i.e.:
print_r($results);
Then you simply need to access the data using the array.
It will be something like $results[1]['torrent_size'];.

JSON: is this a json array?

"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
I know that this is a json array.
I want to do something like this:
"employees":[
"manager":{"firstName":"John", "lastName":"Doe"},
"boss1":{"firstName":"Anna", "lastName":"Smith"},
"boss2":{"firstName":"Peter","lastName":"Jones"}
]
Is this json format? Is this a json array?
No, this is not JSON array, you can check it on this link https://www.jsoneditoronline.org/ just past your code on the left side, and surround it with {} , and you will see where the problem is. Also you can test JSON there in the future.
My suggestion is to use something like this.
"employees":[
{"position":"manager", "firstName":"John", "lastName":"Doe"},
{"position":"boss1", "firstName":"Anna", "lastName":"Smith"},
{"position":"boss2", "firstName":"Peter","lastName":"Jones"}
]
This would be valid JSON array.
If you add some { and } you can make it valid jsons, like this:
{"employees":[
{"manager":{"firstName":"John", "lastName":"Doe"}},
{"boss1":{"firstName":"Anna", "lastName":"Smith"}},
{"boss2":{"firstName":"Peter","lastName":"Jones"}}
]}
I tested it on https://www.jsoneditoronline.org/ and this is valid. Without the need to add the extra "position".

CakePHP json output

I am trying to output the content i get from my Controller in my view as json, but i think i is outputting weird.
On the web i search json and it comes up with output looking like this:
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
However mine is just not formatted and looks like this.
[{"Customer":{"id":"1","first_name":"Ian","last_name":"Smith","address_1":"10 High Streets","address_2":"","town_city":"Plymouth","county":"Devon","postcode":"PL1 2JD"}},{"Customer":{"id":"2","first_name":"David","last_name":"Smith","address_1":"52 Low Avenue","address_2":"","town_city":"Exeter","county":"Devon","postcode":"EX2 1KO"}}]
How can i output it so it looks like the first one?
EDIT
Controller
$user = $this->Customer->find( 'all' );
$this->set( 'users', $user );
View
<?php echo json_encode($user); ?>
There is no sense to beautify your json on output step. If it matters, you may use external tools to make a pretty look of json.
Also, consider using (JSON View) in Cake.
In short, you set a special view variable with content you want to jsonify:
for local effect, write in your action Router::parseExtensions()
specify variable which contains your data to be output $this->set('_serialize', array('response')); (in json, there will be a root object called "response" with content of $response variable).
With such approach, you won't need to create view files - json will be output automatically if request has "Accept: application/json" header.
Only difference in those json responses are that the first one is JSON object with sub objects and second one is an array of JSON objects with their sub objects.
The code below retrieves all records for customers. And when you encode it into json object, it is encoded as array of Cutomers
$this->Customer->find( 'all' );
You can achieve response like the first one by
$this->Customer->find( 'first' );
The above code will only yield one Customer object.

Resources