I'm receiving some JSON via a HTTP POST Callback to a PHP page and I'm having an issue parsing out the JSON. Here's an example of what the JSON data that is sent looks like:
[
{
"type" : "message-received",
"time" : "2016-09-14T18:20:16Z",
"description" : "Incoming message received",
"to" : "+12345678902",
"message" : {
"id" : "14762070468292kw2fuqty55yp2b2",
"time" : "2016-09-14T18:20:16Z",
"to" : ["+12345678902"],
"from" : "+12345678901",
"text" : "Hey, check this out!",
"applicationId" : "93de2206-9669-4e07-948d-329f4b722ee2",
"media" : [
"https://messaging.bandwidth.com/api/v2/users/{accountId}/media/14762070468292kw2fuqty55yp2b2/0/bw.png"
],
"owner" : "+12345678902",
"direction" : "in",
"segmentCount" : 1
}
}
]
I'm then processing this as follows:
$eventJSON = file_get_contents('php://input');
$event= json_decode( $eventJSON );
$eventType = $event->type;
but I'm not getting anything so far for my $eventType variable - I think the issue might be that the JSON is an array but I'm not sure how to handle this?
To parse json try
$eventType = $event[0]->type;
Refer :- How do I extract data from JSON with PHP? to know the difference between object properties and array elements
Related
I am using MongoDB with the PHP Library. I inserted a valid JSON document inside MongoDB using PHP. I am now retrieving the document using findOne and am getting a MongoDB\Model\BSONDocument object as a result. How do I get back my JSON document easily? Is there any inbuilt function or will I have to write logic to convert the BSONDocument to JSON?
I didn't see any answers here and I was having the same issue. I did some research and it appears that when you create a document of MongoDB\Model\BSONDocument there is a bsonSerialize() method. This method will return a stdClass Object which is really the PHP Array Class. According to documentation one can then convert from PHP to BSON and then to JSON.
This is crazy looking, but it works. Here is my example $accountResultDoc is of MongoDB\Model\BSONDocument type.
$json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($accountResultDoc))
Results
{
"_id": {
"$oid": "56e1d8c31d41c849fb292184"
},
"accountName": "Michael's Test Company",
"accountType": "Partner",
"subsidiary_id": {
"$oid": "563c3ffbaca6f518d80303ce"
},
"salesforceId": "WERWERWEr2",
"netsuiteExternalId": "56e1d8c31d41c849fb292184",
"suspendBilling": false,
"testAccount": false,
"serviceOrder_ids": null,
"invoice_ids": null
}
The BSONDocument object has a jsonSerialize method. Use that:
Example
{"_id" : 12345,
"filename" : "myfile",
"header" : {
"version" : 2,
"registry" : "test",
"serial" : 20080215,
"records" : 17806,
"startDate" : 19850701,
"endDate" : 20080214
},
}
$connect = new MongoDB\Client('mongodb://yourconnection');
$db = $connect->YourDB;
$collection = $db->YourCollection;
$test = $collection->findOne(array("_id"=>12345));
$data = $test->jsonSerialize();
echo $data->_id;
echo $data->filename;
Will output this:
12345
myfile
Another way would be:
json_encode( $bsonDoc->getArrayCopy() );
I had the same problem and this is how I accessed the values inside. This works with find.
foreach ($result as $entry) {
echo $entry['_id'], $entry['val1'], ['val2'];
}
Hope this helps someone.
I have a directory into which some json files are regularly updated. What I want to do is deserialize them in my Symfony2 application to get at their juicy data.
The examples on the symfony site include extremely simple flat JSON examples, that do not reflect the nested reality of real world nested JSON data. For example, the following is a simplified version of the files I want to deserialize.
{
"uid" : "some unique identifier"
"title" : "this is a tile",
"description" : "some description",
"paragraphs" : [
{
"position" : "left",
"body" : "a lot of text here",
"video":{
"ogg" : "path1",
"webm" : "path2",
"mp4" : "path3"
}
},
{
"position" : "right",
"body" : "a lot of text here",
"video":{
"ogg" : "path1",
"webm" : "path2",
"mp4" : "path3"
}
}
]
}
Of course, I want to deserialize this nested JSON into a simple, easy to access, model.
What I want to know is how to write the Content class for the above JSON so that when I call $filecontent = $serializer->deserialize($data, 'Acme\Content', 'json'); it deserializes successfully.
This should deserialize your JSON with ease:
$fileContent = json_decode($jsonData);
Documentation for json_decode can be found here
I got a task to get to find out ER from json files this is the one record
{ "__v" : 0, "_id" : ObjectId( "52210bf6880b9f0200000003" ), "email" : "", "emailFrequency" : "instant", "feedbackRating" : 0, "field_aboutMe" : "On Fridays I like to eat apples.", "field_contact" : "me#matt.is", "field_intro" : "Sparkboard bug-fixer. Co-founded Hacking Health, Bodo Wellness, and BrainTripping.", "first_time" : false, "hash" : "", "name" : "Matt Huebert", "picture" : "https://www.ssss.com", "ready" : true, "roles" : [ "admin" ], "email" : "", "tags" : [ "Developer", "Designer", "Mentor" ], "updatedAt" : Date( 1384115378947 ), "votesByDomain" : { "sadsard-com" : "525eadf50f13910200000004" } }
after searching i found out it has something to do with MongoDB . I need to parse this data to find out Entities in it . when i check its validation its not a valid json as its been generated by mongo db .
Please any body have any idea ?
Ive tried this as well
$data = file_get_contents('json/users.json');
bson_decode($data);
tried json_decode as well its also not working and returning NULL
I get this error while trying to bson_decode
Fatal error: Uncaught exception 'MongoException' with message 'type 0x5f not supported
Not sure what has dumped this into your json file, possibly from stdout of mongo shell, But this part is the problem:
ObjectId( "52210bf6880b9f0200000003" )
You need to remove the Wrapping "ObjectId(" and closing brace ")" in order to make each line valid JSON. Once that is filtered you are left with valid JSON.
If you know who is providing you with these files, and cannot use the mongodb datasource directly, then ask them to please use mongoexport, which will at least give you valid JSON from the start.
I'm trying to loop through some JSON data and pull out specific values. Here is the JSON data and the partially working code.
$jsondata = '
[
{
"id" : "421356",
"trip_update" : {
"trip" : {
"trip_id" : "421356",
"start_time" : "12:05:00",
"start_date" : "20130926",
"route_id" : "15"
},
"stop_time_update" : {
"stop_sequence" :70,
"departure" : {
"delay" : 240,
"time" : 1380215057
},
"stop_id" : "6090"
},
"stop_time_update" : {
"stop_sequence" :71,
"departure" : {
"delay" : 240,
"time" : 1380215075
},
"stop_id" : "6095"
}
}
}]';
$result = json_decode($jsondata);
foreach($result as $value) {
echo "trip_id: ".$value->trip_update->trip->trip_id;
if (gettype($value->trip_update ) == "object") {
foreach($value->trip_update as $item) {
echo " - stop_sequence: ".$item->stop_sequence;
}
}
}
I can get the first level of data under 'trip_update->trip'. But there can be any number of 'stop_time_update' data within 'trip_update' as well. Since this data relates to the trip_update data, I need to loop through it and correlate it.
The end goal is to save this data to a database (not shown in the code), so for clarity, this would be the simplified 2 rows of DB data I would like to save in this example:
trip_id,stop_sequence
421356,70
421356,71
There can be any number of stop_sequences in the source data.
Here is an interactive link to the code for you to edit or mess with:
http://sandbox.onlinephpfunctions.com/code/f21ca8928da7de3e9fb351edb075d0a446906937
You might get better results if you write your own parser or use a stream-parser with callbacks. Here's a PHP implementation of such a parser that works with callbacks. So instead of reading the whole JSON data into memory, the parser will read the data in chunks and notify your "listener-class" whenever a new object starts or a property was read in etc. By doing this, you should get separate callback events for each stop_time_update property instead of just one value in the parsed array.
Very similar to what SAX is for XML.
Hi maybe you can change the name.
function next_update($coincidencias){
$replace=$coincidencias[0].$GLOBALS["json_stop_time_update"]++;
return $replace;
}
$result= preg_replace_callback("/stop_time_update/","next_update",$jsondata);
$result = json_decode($result);
You should rework your JSON - you have multiple keys with the same name, try to do print_r($result) to see what I am talking about - PHP will override the "stop_time_update" key time after time and you will be able to access only the last entry. Instead, you should organize your JSON like that:
[
{
"id" : "421356",
"trip_update" : {
"trip" : {
"trip_id" : "421356",
"start_time" : "12:05:00",
"start_date" : "20130926",
"route_id" : "15"
},
"stop_time_update" : [{
"stop_sequence" :70,
"departure" : {
"delay" : 240,
"time" : 1380215057
},
"stop_id" : "6090"
}, {
"stop_sequence" :71,
"departure" : {
"delay" : 240,
"time" : 1380215075
},
"stop_id" : "6095"
}]
}
}]
then you will be able to iterate through your data like this:
foreach($result[0]->trip_update->stop_time_update as $update)
{
$time = $update->departure->time;
...
}
If you cannot change the data structure, then what probably could help you is a PULL parser - one that does not return parsed data structure, but allows you to use a data stream instead - this way you could iterate over each node. The only one I managed to find is an extension to PHP:
https://github.com/shevron/ext-jsonreader
Check the usage section.
This JSON response is invalid because it contains duplicate keys but JSON doesn't allow duplicate keys.
You should contact the service you're trying to request this response from.
If you have a valid JSON response then you can decode it using the json_decode function which returns an object or an array (depends on the second parameter);
You cannot use a JSON parser for this as it will always overwrite the first element due to the same keys. The only proper solution would be asking whoever creates that "JSON" to fix his code to either use an array or an object with unique keys.
Another option is to write your own decoder function for parse it
I'm using jQuery AJAX to load part of my web page. And my AJAX datatype is HTML. I've heard JSON is faster and I've used it too. But JSON doesn't seem to work when the data is a little big, for example:
It works when the data is short:
{"name" : "John Smith" , "age" : "32" , "status" : "married" }
{"name" : "Bella Gilbert" , "age" : "26" , "status" : "single" }
But not when the data is a little big:
{"name" : "John Smith" , "age" : "32" , "status" : "married" }
{"name" : "Bella Gilbert" , "age" : "26" , "status" : "single" }
{"name" : "Joseph Morgan" , "age" : "28" , "status" : "single" }
{"name" : "Paul Wesley" , "age" : "24" , "status" : "single" }
Is there any way I can just fetch the data without stating dataType as JSON and then decode it using javascript, as similar to PHP's function:
json_decode($data);
Or if not then please suggest a way to handle large JSON data using jQuery AJAX. Thanks!
use this
var obj = jQuery.parseJSON(json_data);
It will decode the json_data
http://api.jquery.com/jQuery.parseJSON/
use JSON.parse() to convert a JSON string to an object:
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
// Output: Aaberg, Jesper
jquery version: (Parses a JSON string.)
var obj = jQuery.parseJSON('{"name":"John"}');
alert(obj.name);
You could use the $.parseJSON() method to parse a JSON encoded string into the corresponding javascript object. But if you are performing an AJAX request to your server and the data is coming from it you don't need to use this method at all because jQuery will automatically parse the result passed to the success function:
$.ajax({
url: '/somescript.php',
dataType: 'json',
success: function(result) {
// result is already a parsed javascript object that you could manipulate directly here
}
});
And if you write your server side script properly so that it sets the response Content-Type HTTP header to application/json (which you should always be doing anyways) you don't even need to indicate to jQuery the dataType parameter. jQuery will analyze this response header and automatically parse the result for you:
$.ajax({
url: '/somescript.php',
success: function(result) {
// result is already a parsed javascript object that you could manipulate directly here
}
});
the jQuery.parseJSON method can do this.
Your json object is malformed. Should look like this:
[{"name" : "John Smith" , "age" : "32" , "status" : "married" },
{"name" : "Bella Gilbert" , "age" : "26" , "status" : "single" },
{"name" : "Joseph Morgan" , "age" : "28" , "status" : "single" },
{"name" : "Paul Wesley" , "age" : "24" , "status" : "single" }]
Use this tool to check your object.