I've been trying to figure out how to reformat multiple JSON files into a single one using php, but am having a difficult time understanding how to use complex regular expressions. Suppose I hade multiple instances of the following JSON data:
{
"felines": {
"cats": [
{
"age": 7,
"name": "frank"
},
{
"age": 4,
"name": "popeye"
}
]
},
"canines": {
"dogs": [
{
"age": 2,
"name": "lucy"
},
{
"age": 12,
"name": "wilson"
}
]
}
}
Lets say I had 2 instances of this JSON object in a php script, and wanted to create a single JSON object that combined both "feline" objects from the two separate JSON instances I had, removing the "canines" objects. The file I'd ultimately want would look like this:
{
"felines": {
"cats": [
{
"age": 7,
"name": "frank"
},
{
"age": 4,
"name": "popeye"
}
]
},
"felines": {
"cats": [
{
"age": 6,
"name": "sam"
},
{
"age": 4,
"name": "kelly"
}
]
}
}
Does anyone know how i might be able splice and combine these JSON objects with regular expressions using php?
Thanks.
why don't you use json_encode & json_decode to do the works on php arrays seems to be a lot more easy then doing that with regular expressions.
I doubt this is a problem you should try to solve with regexes. Consider converting the JSON files to associative arrays, do your merging, and then change back to JSON.
Regular expressions are, in general, really bad at dealing with arbitrarily nested contexts like JSON data, HTML tags, programming languages, etc. Some extended regular expression libraries patch around those deficiencies.
But, really, is there a reason you need to do this in JSON itself? And with regex? You're probably going to have a much easier time deserializing the data to real PHP data structures, and merging/manipulating things there. Then, when you're done, re-serialize the result.
The best way to do it would be as RageZ suggested, using json_encode and json_decode, however JSON doesn't allow you to have the same key name, does it? The best you can get would be this:
{
"felines": {
"cats": [
{
"age": 7,
"name": "frank"
},
{
"age": 4,
"name": "popeye"
},
{
"age": 6,
"name": "sam"
},
{
"age": 4,
"name": "kelly"
}
]
}
}
Related
My API call returns a pretty big JSON result and my initial thought was to parse out the two pieces of data I need for each event and create my own array. Does it make more sense to pass around the returned JSON or clean it up for my use throughout the application.
Which is more efficient?
Below is an example of one "Event" each result may have 20-50 events in the data. All I need is the ['resultsPage']['results']['event']['location']['lng'] and ['resultsPage']['results']['event']['location']['lat']:
{
"resultsPage": {
"results": {
"event": [
{
"id":11129128,
"type":"Concert",
"uri":"http://www.songkick.com/concerts/11129128-wild-flag-at-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"Wild Flag at The Fillmore (April 18, 2012)",
"start": {
"time":"20:00:00",
"date":"2012-04-18",
"datetime":"2012-04-18T20:00:00-0800"
},
"performance": [
{
"artist": {
"id":29835,
"uri":"http://www.songkick.com/artists/29835-wild-flag?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"Wild Flag",
"identifier": []
},
"id":21579303,
"displayName":"Wild Flag",
"billingIndex":1,
"billing":"headline"
}
],
"location": {
"city":"San Francisco, CA, US",
"lng":-122.4332937,
"lat":37.7842398
},
"venue": {
"id":6239,
"displayName":"The Fillmore",
"uri":"http://www.songkick.com/venues/6239-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
"lng":-122.4332937,
"lat":37.7842398,
"metroArea": {
"id":26330,
"uri":"http://www.songkick.com/metro_areas/26330-us-sf-bay-area?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"SF Bay Area",
"country": { "displayName":"US" },
"state": { "displayName":"CA" }
}
},
"status":"ok",
"popularity":0.012763
}, ....
]
},
"totalEntries":24,
"perPage":50,
"page":1,
"status":"ok"
}
}
My subjective answer is to just use the entire response in your application, grabbing only what you need when you need it. Taking the time to extract only the data you need might be an unnecessary optimization, and your time could be better spent elsewhere.
Optimize only what you measure. If you can measure your application execution time, perhaps with the help of a profiler, like this one with Xdebug, then you can use data to make an informed decision to optimize in this way. My guess is that your application could use optimizations elsewhere before you make this one, but again, without data, it's just a guess.
I am getting json array after getting applying query logic.
[
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-20"
},
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "CRP",
"booking_date": "2018-05-20"
},
{
"id": "4",
"diag_name": "Seepz Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-21"
}
]
But i want a more justified json array written below.
[
{
"diag_name": "LT Diagnostics",
"test_name": [
{
"id": "3",
"name" : "Alk PO4"
},
{
"id": "3",
"name" : "CRP"
}
],
"booking_date": "2018-05-20"
},
{
"diag_name": "Seepz Diagnostics",
"test_name": [
{
"id": "4",
"name" : "Alk PO4"
}
],
"booking_date": "2018-05-21"
},
]
I am not getting it,How to do in php. I want a more consolidate json format.
Have you tried changing your SQL query to group by diag_name and booking_date? That would be the first step I’d employ to get the outer data.
Formatting the data in the nested manner you’re after could be a function of whatever record serializer you’re using — does it support nested JSON as a return type, or only flat JSON as your example return value shows?
If the record set -> JSON serializer only ever returns flat data, the comments above are correct that you will have to write your own formatter to change the shape of the JSON yourself...
The accepted answer of this other question may be of help:
Create multi-level JSON with PHP and MySQL
I'm not a PHP guy but this is a typical scenario to use functional programming by means of the monad Map.
Looking online I've found this article that could help you.
Changing datasource output is not always (seldom indeed) a viable option.
Enjoy coding
I look for the most efficient and flexible design pattern for creating dynamically JSON that will be my API for IOS.
In example below (its only basic part) "pages", "container", "buttons" and "inputs" are dynamic. Their number and content depends request.
Now I create it that way:
foreach($pages as $page) {
foreach($containers as $container){
foreach($buttons as $burron){
foreach($inputs as $inputs){
}
}
}
}
The result:
{
"callback": {
"status": true,
"message": "",
"return_data": {
"document": {
"number": 6,
"url": "/path/to/file",
"document_id": 11,
"type": 1,
"date": "2017-10-30",
"pages": [
{
"page_number": 1,
"container": [
{
"lp": 1,
"position": 0,
"buttons": [
{
"type": 1,
"header": "Button name",
"inputs": [
{
"type": 0,
"x_pos": 160,
"y_pos": 3441,
"lp": 2
I hope that my question is clear. Thanks for all advice.
The topic that you're describing is called serialization. Basically, it's converting any data structure from one format to another. In your case you want to convert an object or array to JSON. There are several tools in PHP that help with that. For multidimentional arrays or stdClasses, you can use json_encode(). For more complex objects, you can use a serializer library, for example JMS Serializer.
I have a key in my document whose structure is as follow:
"tag": [
{
"schemeName": "http:\/\/somesite.com\/categoryscheme2",
"name": "Test Tag2",
"value": 1,
"slug": "test_tag2"
},
{
"schemaName": "http:\/\/somesite.com\/categoryscheme3",
"name": "Test Tag3",
"value": 1,
"slug": "test_tag3"
}
]
Now, I get inputs as tag=test_tag2ANDtest_tag3. How can I write a query for this?
I tried to iterate through the loop but I didnt got any results.
Correct me if I am wrong but you don't need an $and or $elemMatch, instead:
$mongodb->collection->find(array('tags.slug'=>array(
'$in' => array('test_tag2','test_tag3'))))
Should work, however, if your English suggests what a second read does, then you can also use $all in place of $in. This will ensure that all root documents must have those slugs in them.
use $elemMatch operator to match elements inside the array.
I have the following json data:
{
"data": [
{
"name": "The Frugalicious Chef",
"category": "Chef",
"id": "186397894735983",
"created_time": "2011-03-07T16:10:35+0000"
},
{
"name": "Siuslaw Broadband",
"category": "Telecommunication",
"id": "190373850988171",
"created_time": "2011-03-06T20:21:42+0000"
},
{
"name": "Paul",
"category": "Movie",
"id": "129989595478",
"created_time": "2011-03-04T19:55:18+0000"
},
{
"name": "Mark Zuckerberg",
"category": "Public figure",
"id": "68310606562",
"created_time": "2011-02-16T09:50:35+0000"
},
The idea here is that I want to take this data and use parts of it. I want to create a list of the "category's" that are in the data. The problem is that there is and will be multiple items with the same category. So my list will have duplicates that I do not want. The following is how I am getting the data and converting it for use:
$jsonurl = "https://xxxxxxxxxx.com/".$fd_ID. "/info?access_token=".$session['access_token'];
$likesjson = file_get_contents($jsonurl,0,null,null);
$likesArray=json_decode($likesjson);
I then use a foreach to access the data.
foreach($friendLikesArray->data as $l)
{
etc......
}
So I guess muy question is I want to take the $likesArray and pull out all the unique Data->Category->names. Also will want to do sorting, and other things but I will get to that when the time comes.
Thanks for the help in advance.
Neil
The data structure you would want to use is a set, that only allows unique entries.
A simple implementation using PHP arrays is to use the keys.
e.g.
$categories = array();
foreach($friendLikesArray->data as $l)
{
$categories[$l->category] = true;
}
$categories = array_keys($categories);
This way if the category has already been added, then you are not adding anything new to the array.
If the keys are not important to you then you can use the line:
$categories[$l->category] = $l->category
But this means your array won't have 0,1,2...n for keys.