merging json objects in php - json

how can i merge two json objects in php
one of array is like this
$arr_data = array('id'=>$country_id);
$arr = json_encode($arr_data);
and another one is like this:
$arr_places = json_encode($xmlDoc);
now I want to merge them into a single json object. How can I do this.

It depends very much on what you mean by "merge". Just a plain merge or you will need to eliminate the duplicated attributes?...etc.
The simplest way is just like what xdazz mentioned.

So you should merge the array first and then use json_encode.
$json = json_encode(array_merge($arr_data, $xmlDoc));

Merge the results and then encode.
$arr_data = array('id'=>$country_id);
$res = array_merge( $arr_data, $xmlDoc );
$merged = json_encode($res);

Most of the answers here assume that this is a case where one is confronted with two arrays, rather than objects. OP was asking about merging two objects into a single JSON.
While there are many solutions to this, I've got a hack that goes a step further and actually merges the objects into a single JSON string by converting the objects to JSON strings, then back to associative arrays, and then back to JSON.
Could be an efficiency fail, but does the job :-) Here's a code sample:
/**
* Merges two objects into a single JSON structure
* #param object $obj1
* #param object $obj2
* #return string the resuling JSON string
*/
function mergeToJSON($obj1, $obj2) {
$json1 = json_encode($obj1);
$json2 = json_encode($obj2);
if ($json1 === FALSE OR $json2 === FALSE) {
return "";
}
$array1 = json_decode($json1, TRUE);
$array2 = json_decode($json2, TRUE);
$data = array_merge($array1, $array2);
return json_encode($data);
}

The above mentioned solution is not working for me with PHP version 5.5.12
What I want to is in short append to json strings and form one json string out of it, as explained below:
$str1 = {
timestamp: "2015-04-03T08:08:51+00:00",
user: "admin",
src_ip: "127.0.0.1"
}
$str2 = {
timestamp: "2015-04-03T08:08:51+00:00",
user: "Peter_x",
src_ip: "127.0.0.1"
}
$value1 = json_decode ($str1, TRUE);
$value2 = json_decode ($str2, TRUE);
$combined = array_merge ($value1, $value2);
$combined_json = json_encode ($combined);
file_put_contents("c:\outputfile", $combined_json, FILE_APPEND);
The result is:
{
"timestamp": "2015-04-03T08:08:51+00:00",
"user": "admin",
"src_ip": "127.0.0.1",
}
{
"timestamp": "2015-04-03T08:08:51+00:00",
"user": "Peter_x",
"src_ip": "127.0.0.1",
}
Instead I expect one single json string. Firefox fails to parse it. What surprises me is that in the resulting string the keys are within quotes. (e.g: "timestamp").
Can any one tell me what is wrong with the code or how to join the two json strings to one?

Related

Selecting Data from JSON via PHP

I have json data and i want to select some data plese read the json
"response":{"status":1,"httpStatus":200,"data":{"page":1,"current":0,"count":982,"pageCount":1,
"data":{"1131":{"OfferFile":
{"offer_id":"547"}},
"1525":{"OfferFile":{"offer_id":"717"}}
}
From above data i want to select 1131 and 1525 integers via php
Please give me a code snd thanks.
I am assuming that the actual JSON that you have, when formatted properly, looks as follows:
{
"status":1,
"httpStatus":200,
"page":1,
"current":0,
"count":982,
"pageCount":1,
"data":{
"1131":{
"OfferFile":{
"offer_id":"547"
}
},
"1525":{
"OfferFile":{
"offer_id":"717"
}
}
}
}
If so, you would get the integers with the following code:
$json = json_decode($string, true);
$ids = array_keys($json['data']);
Use json_decode to parse your :
$json = json_decode('{..your data..}', true);
$data = $json['data']['data'];
The $data variable is an array. To get "1131" and "1525", you need to get array_keys of $data via :
$vals = array_keys($data);
$1131 = $vals[0];
$1525 = $vals[1];

Encoding an array of hashes in Perl

I'm trying to do something that seems to be very simple, but I can't figure out how to do it in Perl : I want to output a JSON-formatted array of hashes.
The array of hashes in question is actually an array of DBIx::MyParse Items object instances. Here is my code :
use strict;
use DBIx::MyParse;
use JSON::PP;
my $json = JSON::PP->new->ascii->pretty->allow_nonref;
our $parser = DBIx::MyParse->new( database => "test", datadir => "/tmp/myparse" );
our $query = $parser->parse("UPDATE table1 SET field1 = 1;");
$json->convert_blessed(1);
print $json->encode(#{$query} );
And this is what this script outputs :
"SQLCOM_UPDATE"
Which is actually the first element of the array that I want to output as a whole. Here is the content of the array that I see when I step-by-step debug the script :
I would like to have the whole structure in my JSON output. How can I achieve this ?
JSON::encode just expects a single argument, not a list. Use $json->encode( $query ).

Json_Decode Object Remains NULL / Empty

I have a json_decoded response that looks like this:
string(664) "{ "ticker": "AAPL:US" }"
Now I am using json_decode with 'true' to access the data as an object:
print_r(json_decode($res));
When trying to dump the content it remains NULL
var_dump($res->ticker);
How would I access the data without an array just the object?
EDIT: It remains 0 when using an array or an object. Same result
There are two major issues with your code:
1) When your second parameter is set to true, returned object will be converted into associative array. You have to set it to false (it's default value anyway).
2) json_decode does not change the value of $res, instead, it will return value encoded in json in appropriate type (mainly object or associative array).
Try this:
$res = '{ "ticker": "AAPL:US" }';
$obj = json_decode( $res, false );
var_dump( $obj );

Database json column returning escaped string in laravel blade

I have saved some Json data in a MySQL column. While fetching the data to a Laravel Blade application the json fields are all escaped. Hence, I am facing issues while reading the json data.
[
{
"id": "1",
"json_backup": "{\"id\":\"2\",\"organization_id\":\"1\",\"amount\":\"7800.00\",\"date\":\"2015-05-11\",\"created_at\":\"2015-05-11 07:20:45\",\"updated_at\":\"2015-05-11 07:20:45\"}",
"ip": "127.0.0.1",
"created_at": "2015-05-12 12:21:16",
"updated_at": "2015-05-12 12:21:16"
}
]
The json_backup field in the above example is escaped. How do I ensure that this field is not escaped.
Code to fetch the data
$activity = Activity::find(1);
In the View:
#foreach ($activities AS $activity)
#foreach($activity->json_backup AS $order)
#endforeach
#endforeach
Error:
Invalid argument supplied for foreach()
Any help would be much appreciated.
#saaz When you are storing the JSON in MySQL, use
json_encode($json_backup, JSON_UNESCAPED_SLASHES)
HTH
This error is coming on the second foreach section.
Please try it in somewhat this way.
$json = json_decode($activity->json_backup, true);
This would work but can't say it definitely. And even if you have problem refactor the code and create a class with following code:
function escapeJsonString($value) {
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
And simply say
$json = escapeJsonString($activity->json_backup);
This one would definitely work. Hope so this helps.

Perl to JSON, with key/value pairs

I am trying to output some data from Perl to JSON. I can do a simple output, but would like to structure it better.
I have an array with an id, a start time and an end time. This is the code I am using to output:
print header('application/json');
my $json->{$entry} = \#array;
my $json_text = to_json($json);
print $json_text;
Which returns:
{"Season":[["1","1330065300","1344038401"],["7","1298505601","1312416001"]]}
But I would like to output something more like:
{"Season":0[{"id":1,"DateStart":1330065300,"DateEnd":1344038401},{"id":7,"DateStart":1298505601,"DateEnd":1312416001}]}
Can anyone help on how to better structure my output?
---UPDATE------
Thanks Michael. I have tried to implement your example.
This is the code at the moment:
foreach my $key (keys %$seasons)
{
$seasons->{$key} =
[
map
{
{ id=>$_[0], DateStart=>$_[1], DateEnd=>$_[2] }
} #{$seasons->{$key}}
];
}
But it returns the error (referring to the foreach line):
Not a HASH reference at line 148
$seasons is an arrayref return from a SQL fetchall_arrayref
Any clues?
You basically want to convert an array of arrays to an array of hashes, and you can do this using map. Assuming $data is your structure, this should do it:
for my $key (keys %$data) {
$data->{$key} = [
map {
{ id => $_->[0], DateStart => $_->[1], DateEnd => $_->[2] }
} #{$data->{$key}}
];
}
If you want to output an array of objects with key/value pairs instead of an array of arrays, then put appropriate data into to_json in the first place.
i.e. an array of hashrefs and not an array of arrayrefs.
You can use map to transform the data.
Whenever you're trying something like this, always check CPAN to see if someone has done it before and not try to reinvent the wheel. I found a module called JSON that seems to do exactly what you want.
There's an example on that page that does exactly what you want. Here's a quick paraphrase:
use JSON; # imports encode_json, decode_json, to_json and from_json.
# simple and fast interfaces (expect/generate UTF-8)
my $utf8_encoded_json_text = encode_json \#array;
Can't get easier than that. The best part is that this will work no matter how complex your array structure gets.