How to create a JSON object - php

I am trying to create an JSON object out of a PHP array. The array looks like this:
$post_data = array('item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts);
The code to encode the JSON look like this:
$post_data = json_encode($post_data);
The JSON file is supposed to look like this in the end:
{
"item": {
"is_public_for_contacts": false,
"string_extra": "100000583627394",
"string_value": "value",
"string_key": "key",
"is_public": true,
"item_type_id": 4,
"numeric_extra": 0
}
}
How can I encapsulate the created JSON code in the "item": { JSON CODE HERE }.

Usually, you would do something like this:
$post_data = json_encode(array('item' => $post_data));
But, as it seems you want the output to be with "{}", you better make sure to force json_encode() to encode as object, by passing the JSON_FORCE_OBJECT constant.
$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);
"{}" brackets specify an object and "[]" are used for arrays according to JSON specification.

Although the other answers posted here work, I find the following approach more natural:
$obj = (object) [
'aString' => 'some string',
'anArray' => [ 1, 2, 3 ]
];
echo json_encode($obj);

You just need another layer in your php array:
$post_data = array(
'item' => array(
'item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts
)
);
echo json_encode($post_data);

You could json encode a generic object.
$post_data = new stdClass();
$post_data->item = new stdClass();
$post_data->item->item_type_id = $item_type;
$post_data->item->string_key = $string_key;
$post_data->item->string_value = $string_value;
$post_data->item->string_extra = $string_extra;
$post_data->item->is_public = $public;
$post_data->item->is_public_for_contacts = $public_contacts;
echo json_encode($post_data);

$post_data = [
"item" => [
'item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts
]
];
$post_data = json_encode(post_data);
$post_data = json_decode(post_data);
return $post_data;

Related

how to add json serilize data into the database using php

This is my array and i want to convert this as json and added to the database
Array(
[0] => Array
(
[id] => e4da3b7fbbce2345d7772b0674a318d5
[channel] => Array
(
[0] => 1
[1] => 2
)
)
)
I want to store data like this where id remain same and channel will add to the next json bracket with same id
[{"id":"e4da3b7fbbce2345d7772b0674a318d5","channel":1},{"id":"e4da3b7fbbce2345d7772b0674a318d5","channel":2}]
Code
$var1 = array([
'id' => $hash_user,
'channel' => $channel
]);
// print_r($var1);
foreach($var1 as $id){
$encode_data = $id['id'] . $id['channel'][0]. $id['id'] . $id['channel'][1];
$see = json_encode($encode_data);
}
print_r($see);
print_r($encode_data);
//
die;
$info['user_hash'] = $encode_data;
You should be clear in your post. But given the information, I assume you need to change the array you have to that JSON.
What you have:
$databaseArray = [[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => [1,2]]];
$json = json_encode($databaseArray);
What you want:
$databaseArray = [[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => 1]];
$json = json_encode($databaseArray);
What you need to change:
$databaseArray = [
[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => [1,2]],
[ "id" => "1235437fbbce2345d7772b0674a32342", "channel" => [1,2]]
];
$databaseMergedArray = [];
// You need to set the channel to a value instead of array.
foreach($databaseArray as $key => $item) {
foreach($databaseArray[$key]["channel"] as $channel) {
$item["channel"] = $channel;
$databaseMergedArray[] = $item;
}
}
$json = json_encode($databaseMergedArray);
echo ($json);

PHP create value variable for json_encode function

I'm using a JSON API; I want to create a variable with values and then convert it to a JSON string via json_encode. The (working) JSON string is this:
$data = '
{
"function":"setArticleImages",
"paras":{
"user":"'.$user.'",
"pass":"'.$pass.'",
"product_model":"'.$productsModel.'",
"images":{
"products_id":'.$products_id.',
"image_name":"'.$imageName.'",
"image":"'.$image.'",
"products_images":[{
"products_id":'.$products_id.',
"image_name":"'.$imageName2.'",
"image":"'.$image2.'"
} ]
}
}}
';
I was now trying to write it like this and use json_encode:
$data = array(
"function" => "setArticleImages",
"paras" => array(
"user" => $user,
"pass" => $pass,
"product_model" => $productsModel,
"images" => array(
"products_id" => $products_id,
"image_name" => $imageName,
"image" => $image,
"products_images" => array(
"products_id" => $products_id,
"image_name" => $imageName2,
"image" => $image2,
),
)
)
);
$data = json_encode($data);
Unfortunately it does not work. The problems seems to be at '"products_images" => array('. I don't know how to handle the '[' of the '"products_images":[{' part.
Anyone an idea how to write it in the second code snippet?
You just need to add an extra level of array to the products_images element, so that you get a numerically indexed array of associative arrays, giving you the array of objects form you want:
$data = array(
"function" => "setArticleImages",
"paras" => array(
"user" => $user,
"pass" => $pass,
"product_model" => $productsModel,
"images" => array(
"products_id" => $products_id,
"image_name" => $imageName,
"image" => $image,
"products_images" => array(
array(
"products_id" => $products_id,
"image_name" => $imageName2,
"image" => $image2,
)
),
)
)
);
Demo on 3v4l.org
The "{ }" in th JSON notation is a PHP array with alphanumerical key.
So :
$array = ["foo" => [1,2,3], "bar" => [4,5,6]
will be converted in a JSON string :
{ foo : [1,2,3], bar: [4,5,6]}
So if you are looking to a JSON that looks like this
[{ foo : [1,2,3], bar: [4,5,6]}]
You will have to do an array with numeric keys that contains your alphanumerical array :
$array = [["foo" => [1,2,3], "bar" => [4,5,6]]];
// same as
$array = [ 0 => ["foo" => [1,2,3], "bar" => [4,5,6]]];

PHP json_encode - create JSON array

I've used the json_encode function in the past to create simply JSON objects like this:
$payload = array ("user" => $username, "password" => $password, "group" => $group);
$payload = json_encode ($payload);
which creates this:
{"user":"john smith","password":"abc12345","group":"sales"}
I now need to generate a JSON array like this:
{
"query": [
{
"Date": "11/01/2017...12/31/2017"
}
]
}
but I can't find the correct syntax.
You can simply create a 2d array in php.
$payload = array (
"query" => array(
array(
"date" => "11/01/2017...12/31/2017",
"other sub key" => "other sub value"
)
),
"other main key" => array(
array(
"other sub key" => "other sub value",
etc...
)
)
);
That would be something like this
$array = array(
'query' => array(
array('Date' => '11-01-2017')
)
);
echo '<pre>';
print_r(json_encode($array, JSON_PRETTY_PRINT));
Result
{
"query": [
{
"Date": "11-01-2017"
}
]
}
$payload = json_encode($payload, JSON_PRETTY_PRINT);
reference: http://php.net/manual/en/function.json-encode.php

How can I create a specific JSON string?

I want to create this JSON string with PHP:
[{name:'20140722.1304',data:[[0, 0.224],[0, 0.228]] }, {name:'20140729.1149',data:[[1, 0.224],[1,0.228]] }]
My current attempt:
$jsonArray = array(
'name' => '20140722.1304'
,'data' => array('0' => '0.024', '1'=> '0.028')
);
$jsonValue = json_encode($jsonArray);
echo $jsonValue;
But this code's output looks like:
{"name":"20140722.1304","data":["0.024","0.028"]}
Where did I went wrong? What do I have to change in my code to get to my expected output?
I finally got you to tell us what you want in the comments; please be up-front with this in the future. The expected output you gave differed from your actual output in so many ways that it was impossible to tell what you actually thought the problem was, but:
I want to get the output as {name:'20140722.1304',data:[[0, 0.224],[0, 0.228]]}
At this point, the only difference I can see is that your data is a nested array in your expected output, but not your actual output.
That has nothing to do with JSON. You're just not building your input array correctly.
Try json-encoding this:
$jsonArray = array(
'name' => '20140722.1304'
,'data' => array(array(0, 0.024), array(0, 0.028))
);
<?php
for($i=0;$i<2;$i++)
{
$jsonArray[] = array(
'name' => '20140722.1304'
,'data' => array('0' => '0.024', '1'=> '0.028')
);
}
//$jsonValue = json_encode($jsonArray);
$jsonValue = json_encode($jsonArray,true);
echo$jsonValue;
?>
try this
$jsonArray = array(
'name' => '20140722.1304'
,'data' => array('0' => '0.024', '1'=> '0.028')
);
$out = array_values($jsonArray);
echo json_encode($out);
output:
["20140722.1304",["0.024","0.028"]]
EDit:
$array = array(
2 => array("name" => '20140722.1304'),
4 => array("'data" => array('0' => '0.024', '1'=> '0.028')));
$out = array_values($array);
echo json_encode($out);
output:
[{"name":"20140722.1304"},{"'data":["0.024","0.028"]}]

how to format json with array of json

I want output in json like this
response:{url="www.google.com/raj.png", size=12.344KB},{url="www.google.com/raj2.png", size=12.344KB},{url="www.google.com/raj4.png", size=12.344KB}
But currently i am getting
"url=> www.google.com/img1.png size => 12.344 KB,url=> www.google.com/img2.png size => 12.344 KB"
//Using some loop here
{
$response[] = array('url' => 'url_value','size' => 'file_size');
}
//without loop hardcoded values:
$response = array ( array('url' => "www.google.com/raj.png",'size' => "12.344KB"),
array('url' => "www.google.com/img2.png",'size' => "10.344KB") );
return json_encode($response);
$out= Array(
Array('url'=>'www.goog', 'size'=>'12KB'),
Array('url'=>'moogle', 'size'=>'13KB')
);
echo Json_encode($out);
Not sure how you are formatting your array, but if you define it like this it should do the trick:
$response_array = array(
'response' => array(
array(
'url' => 'www.google.com/raj.png',
'size' => '12.344KB',
),
array(
'url' => 'www.google.com/raj.png',
'size' => '12.344KB',
),
array(
'url' => 'www.google.com/raj.png',
'size' => '12.344KB',
),
),
);
$respose_json = json_encode($response_array);
echo($response_json);
For looping through some results, try something like this:
$response_array = array('response' => array());
foreach($result_set as $result_item) {
$response_item = array();
$response_item['url'] = $result_item['url'];
$response_item['size'] = $result_item['size'];
$response_array['response'][] = $response_item;
}
$respose_json = json_encode($response_array);
echo($response_json);
With the $result_set above being whatever data you've pulled from a DB, server, etc.

Categories