Convert from one json format to another [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a JSON formatted string that i get from an API call. however the format of the JSON string that i get from the API call is something similar to this.
{"offset":1,"result":{"host":"x.x.x.x","count":123"}}
I want it to be in the following format
{"offset":1,"result":[{"host":"x.x.x.x","count":123"}]}
Note: kindly look at the addition square braces in the folded JSON.
How can i achieve this in PHP . Im fairly new to PHP a little help here is appreciated. Thanks :)

You should be able to do this using PHP's json_decode() and json_encode() functions. Something like:
$jsonFromApi = '{"offset":1,"result":{"host":"x.x.x.x","count":123}}';
$array = json_decode($jsonFromApi, true);
$array['result'] = array($array['result']);
$newJson = json_encode($array);
Edit: Here is an example of using foreach for doing this to a series of comma separated json strings.
$originalData = '{"offset":1,"result":{"host":"x.x.x.x","count":123}},{"offset":2,"result":{"host":"x.x.x.x","count":123}},{"offset":3,"result":{"host":"x.x.x.x","count":123}}';
// Convert original data to valid JSON by wrapping it in brackets []. Makes it a JSON array.
$json = '['.$originalData.']';
$array = json_decode($json, true);
$convertedJsonStrings = array();
foreach ($array as $data) {
$data['result'] = array($data['result']);
$convertedJsonStrings[] = json_encode($data);
}
echo implode(',', $convertedJsonStrings);
Here we can't directly use json_decode() for $originalData since it is not valid JSON as it is.

Convert original into JSON object, take out result.
var originalJSONObj = JSON.parse(original);
var result = originalJSONObj.result;
Create another object with modifiedJSONObj.offset = 1 and modifiedJSONObj.result = [] and finally modifiedJSONObj.result.push(result).

In PHP, something like:
$json = '{"offset":1,"result":{"host":"x.x.x.x","count":123}}';
$data = json_decode($json);
$data->result = [$data->result];
$json = json_encode($data);
var_dump($json);

// i fixed the json that you are able to receive from the api
// maybe you could check it also
$data = '{
"offset": 1,
"result": {
"host": "x.x.x.x",
"count": "123"
}
}';
// decode the json from api
$data = json_decode($data, true);
// create new data from decoded data
$new_data = array(
'ofsset' => $data['offset'],
'result' => array(
$data['result']
)
);
// encode it again
echo json_encode($new_data);

Related

How to access data from {string} [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
Some fields save data in the following way in one of my database field:
{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}
(* Don't know how it's called so i wrote string in the title)
How can i access data in particular for every "value".
One way could be to explode for every field but is there a better way to do this?
$ask_for_price_variable = [value from field];
if ($ask_for_price_variable == 'YES') {
// Do something
}
EDIT: As i said i did not know how it was called "JSON" so i could not search for it. Thank you all for the answers.
It is json data. You can access it using json_decode in php
$json = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
$data = json_decode($json,true);
$ask_for_price_variable = $data['ask_for_price_en-GB'];
Use json_decode
$str = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
print_r(json_decode($str, true));
You need to study about JSON type and how to encode or decode to get the data.
try this
echo "<pre>";
print_r( json_decode('{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}'));
to view the result , click run or hit f9, here
try json_decode function
$str = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
$data = json_decode($str, true);
print_r($data);
output:
Array ( [per_meter_en-GB] => TEST_FOR_TEST [roll_40_en-GB] => [ask_for_price_en-GB] => YES )
here you can access required value from $data array eg. echo $data['per_meter_en-GB']; will output TEST_FOR_TEST

How to get value from JSON encode in PHP?

i have searched and searched but i don't know where i'm wrong getting a value from JSON encode, can you help me? Please don't kill me, i'm a newbie :)
My php:
<?php
$data = json_decode("document.json", true);
$getit = $data["likes"];
My JSON:
[{
"title" : "MYTITLE",
"image" : "MYIMAGE",
"likes" : 0
}]
EDIT
Thanks for the help this is now working!
json_decode expects an string, not an filename - so you have first get the contents of the given file. This could be easily achieved with file_get_contents.
Your current json structure contains an array(with currently only one element), which contains an object. So if you want the likes, you have to read the first element of the result array and of that(an associative array), the likes.
$data = json_decode(file_get_contents($filename), true);
$likes = $data[0]['likes'];
If you have more than one object in the given json file, you could loop over the data with foreach
foreach ($data as $element) {
echo "likes of {$element['title']}: {$element['likes']}\n";
}
For json_decode you have to pass JSON string, not a file name. Use file_get_contents to get JSON content and then decode it.
$data = json_decode(file_get_contents('document.json'), true);
$getit = $data[0]['likes'];
Your JSON is an array of objects, you first need to access the first element of your array :
$data[0]
Then you can access the key you want :
$getit = $data[0]['likes'];
Plus, as stated in a comment above, you need to pass a string to json encode, here is an code sample that should suit your needs :
<?php
$data = json_decode(file_get_contents('document.json'), true);
$getit = $data[0]["likes"];
Hope this helps.

How do i split and assign that data? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
How can i split that image or assign an array in PHP.
[{"ID":2,"no":123,"pname":"400","unit":"mt","bid_count":"4568","unit_price":"56","est_unit_price":"21.31","progress_count":"3841","i_project":117,"seq":0}]
I tried to split but it is a little weird.
I use this =>
$object = str_replace('[{', '', $object);
$object = str_replace('}]', '', $object);
$pieces = explode(",", $object);
// return $pieces[0];
$datas = array(
'ID' =>str_replace('"ID":','',$pieces[0]),
'poz_no'=>str_replace('"poz_no":','',$pieces[1]),
'poz_name'=>"asd",
'unit'=>str_replace('"unit":','',$pieces[3]),
'bid_count'=>str_replace('"bid_count":','',$pieces[4]),
'unit_price'=>str_replace('"unit_price":','',$pieces[5]),
'est_unit_price'=> str_replace('"est_unit_price":','',$pieces[6]),
'progress_count' =>str_replace('"progress_count":','',$pieces[7]),
'i_project'=>str_replace('"i_project":','',$pieces[8]),
'seq' =>str_replace('"seq":','',$pieces[9])
);
I did it myself but it seems weird:
$object = str_replace('[{', '', $object);
$object = str_replace('}]', '', $object);
$pieces = explode(",", $object);
$datas = array(
'ID' =>str_replace('"','',str_replace('"ID":','',$pieces[0])),
'poz_no'=>str_replace('"','',str_replace('"poz_no":','',$pieces[1])),
'poz_name'=>str_replace('"','',str_replace('"poz_name":','',$pieces[2])),
'unit'=>str_replace('"','',str_replace('"unit":','',$pieces[3])),
'bid_count'=>str_replace('"','',str_replace('"bid_count":','',$pieces[4])),
'unit_price'=>str_replace('"','',str_replace('"unit_price":','',$pieces[5])),
'est_unit_price'=>str_replace('"','',str_replace('"est_unit_price":','',$pieces[6])),
'progress_count' =>str_replace('"','',str_replace('"progress_count":','',$pieces[7])),
'i_project'=>str_replace('"','',str_replace('"i_project":','',$pieces[8])),
'seq' =>str_replace('"','',str_replace('"seq":','',$pieces[9]))
);
You can use json_decode for this.
If you have your string:
$json = '[{"ID":2,"poz_no":123,"poz_name":"400mm Muflu Beton ve C Parçası Döşenmesi","unit":"mt","bid_count":"4568","unit_price":"56","est_unit_price":"21.31","progress_count":"3841","i_project":117,"seq":0}]';
You can simply do:
$datas = json_decode($json, true);
Now in $datas you have an array with all the fields from json.
As you can see in json you have an array of objects with only one element. If you want only that first element you can do after:
$datas = $datas[0]; //get first element of array.
Your are actually dealing with a JSON encoded Data here. So, you may need to first convert the JSON Data to Standard PHP Object. And then you can simply access your preferred values using normal PHP Object Access Notation. The commented Code below attempts to illustrate (however vaguely) the Idea.
THE GIVEN JSON DATA:
<?php
$jsonString = '[{
"ID":2,
"poz_no":123,
"poz_name":"400mm Muflu Beton ve C Parçası Döşenmesi",
"unit":"mt",
"bid_count":"4568",
"unit_price":"56",
"est_unit_price":"21.31",
"progress_count":"3841",
"i_project":117,
"seq":0
}]';
THE PROCEDURE:
<?php
// CONVERT THE JSON DATA TO NATIVE PHP OBJECT...
$arrJSONData = json_decode($jsonString);
// NOW, YOU COULD ACCESS THE PHP OBJECT BY DOING: $arrJSONData[0]
$objJson = $arrJSONData[0];
// IF YOU DID IT LIKE THIS; FROM THIS POINT YOU COULD ACCESS YOUR DATA
// LIKE YOU WOULD ACCESS ANY NORMAL PHP OBJECT LIKE SO:
$id = $objJson->ID;
$pozNo = $objJson->poz_no;
$unit = $objJson->unit;
// HOWEVER, WHAT IF THE JSON DATA CONTAINS MORE THAN ONE ENTRY?
// THEN A LOOP WOULD BE NECESSARY...
// LOOP THROUGH THE RESULTING ARRAY OF OBJECTS AND GET YOUR DATA...
foreach($arrJSONData as $jsonData){
// AGAIN; YOU COULD ACCESS YOUR DATA
// LIKE YOU WOULD ACCESS ANY NORMAL PHP OBJECT LIKE SO:
$id = $objJson->ID;
$pozNo = $objJson->poz_no;
$unit = $objJson->unit;
}

PHP json_Encode an array of json_encode-ed arrays

Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.
Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()
Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode

Reading multiple json values with php

I am trying to read certain values from a json string in php, I am able to do a simple json string with only one value such as
$json = '{"value":"somevalue"}';
Using this:
<?php
$json = '{"value":"somevalue"}';
$obj = json_decode(json_encode($json));
print $obj->{'value'};
?>
But when i try an get a value from the following json string it throws an error...
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
I validated the json on JSONlint but not sure how to access the values within this with php.
Thanks
You can try this:
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
//since $json is a valid json format you needn't encode and decode it again
$obj = json_decode($json);
print_r($obj->filed);
print_r($obj->rule);
You can pass true as a second parameter to json_decode() to get the results as an array
$my_arr = json_decode($json, true);
var_dump($my_arr);
Should help you. You can then step through the array as you would normally.
use var_dump to print out the object with all it's members and hierarchy. you should then be able to find the value you are looking for

Categories