I'm trying to generate a JSON object using PHP to be passed to the client using data that is already stored in MySQL database.
The database contains a list of multipolygon coordinates like below in a single text field:
[
[
[
[
104.39209000000005,
-4.850154
],
[
108.17138687500005,
-3.721745195827911
],
[
112.12646500000005,
-1.274309
],
[
103.02978499999995,
-3.579213
]
]
]
]
When I try to generate a JSON object using json_encode I get the following:
{
"coordinates": "[[[[104.39209000000005,-4.850154],[108.17138687500005,-3.721745195827911],[112.12646500000005,-1.274309],[103.02978499999995,-3.579213]]]]"
}
And because of the quotes around the coordinates themselves, they are not recognised as JSON object by JavaScript.
I've tried to explode the coordinate string and then put it back together manually but it still needs a lot of hacks to get it working.
Any help in getting this to output as a an actual JSON object in PHP would be much appreciated.
I'm trying to get to this:
{
"coordinates": [
[
[
[
104.39209000000005,
-4.850154
],
[
108.17138687500005,
-3.721745195827911
],
[
112.12646500000005,
-1.274309
],
[
103.02978499999995,
-3.579213
]
]
]
]
}
It's pretty jerry-rigged, but you could do this:
$string = json_encode( $database_value ); // same as you're using now
$string = str_replace( '"', '', $string ); // get rid of the quotes
// wrap them back around 'coordinates'
$string = str_replace( 'coordinates', '"coordinates"', $string );
Simply use json_decode before json_encode, like this:
// This comes from the database, of course
$coords = '[[[[104.39209000000005,-4.850154],[108.17138687500005,-3.721745195827911],[112.12646500000005,-1.274309],[103.02978499999995,-3.579213]]]]';
echo json_encode(array(
'coordinates' => json_decode($coords)
));
This will output nested arrays exactly as you desire:
{"coordinates":[[[[104.39209,-4.850154],[108.171386875,-3.7217451958279],[112.126465,-1.274309],[103.029785,-3.579213]]]]}
Related
This question already has answers here:
How to add square braces around subarray data inside of a json encoded string?
(3 answers)
Closed 6 months ago.
this is the json i have to produce
{
"email": "example#example.com",
"campaign": {
"campaignId": "p86zQ"
},
"customFieldValues": [
{
"customFieldId": "y8jnp",
"value": ["18-29"]
}
]
}
if i use
$data = [
"email" => $_POST['mail'],
"campaign" => [
"campaignId" => "4JIXJ"
],
"customFieldValues" => [
"customFieldId" => "y8jnp",
"value" => ["18-29"]
]
];
and i do json_encode($data)
value is an object, but it should be an array with a single element. Somehow json_encode treats it as an object. Can i force it to treat it as an array with a single element ?
Thanks in Advance
Adrian
At the moment, you have a single array with 2 elements, instead of an array with a single element of a sub-array. In order to get the json in the first section, you need to add another array level.
$data = [
"email" => $_POST['mail'],
"campaign" => [
"campaignId" => "4JIXJ"
],
"customFieldValues" => [
[
"customFieldId" => "y8jnp",
"value" => ["18-29"]
]
]
];
That will give you this:
{
"email": null,
"campaign": {
"campaignId": "4JIXJ"
},
"customFieldValues": [
{
"customFieldId": "y8jnp",
"value": ["18-29"]
}
]
}
if there is one single element in the array the json_encode will treat is as an object and the key of the object is the index of the array
to treat it as an array you can use array_values(<your_array>)
With the help of variable categories i have this array in which all the arrays are without key/default index , because of this when i do $categories as $category in foreach and when i echo $category['name'] it gives illegal sting offet.
using laravel blade
What can be the possible solution for this or should i validate array first?
The above code is in JSON format, convert to array first
for example
$ex = {
'result':"success",
'categories':[{
//your rest of the code
}]
}
$data = json_decode($ex, TRUE);
//next use for each
foreach($data as $key => $value)
{
//rest of your logic
}
I think this is your situation, and in my opinion, you are using the wrong variable to decode let me take your image as an example here.
<?php
$ex = [
'result' => 'success',
'categories' => [
[
'id'=>1,
'name'=>'cat1',
],
[
'id'=>2,
'name'=>'cat21',
],
[
'id'=>3,
'name'=>'cat31',
],
]
];
echo "<pre>";
$res = json_encode($ex);
print_r(json_decode($res));
in this example, I just showed you that I have done json_encode and json_decode easily without any issue and the output of JSON is same as your example image.
Thank You!
My question is a bit different to most like this, I basically want to do the opposite to this question from Haluk.
So I have a JSON string:
{
"main":
{
"title": "QuickPub",
"defaultRole": "BU"
},
"roles":
{
"TU":
{
"name": "testUser",
"code": "TU"
}
}
}
and I want to be able to generate a string containing a php array definition from it:
<?php
return [
"main" =>
[
"title" => "QuickPub",
"defaultRole" => "BU"
],
"roles" =>
[
"TU" =>
[
"name" => "testUser",
"code" => "TU"
]
]
];
?>
EDIT:
I have tried json_decode() but this produces a variable, I need a string that I can put in a php file that will reproduce this without using php_decode.
I think this will solve your problem. First of all convert your json string to an array using json_decode($string,1); then convert that array to string representation using print_r($array,1); this will return your result as array string representation.
For example:
$json='{}' // its a demo
$array= json_decode($json,1); // an array
$result = print_r($array,1);
echo $result;
This is an adaptation of Being Sunny's answer, but using the var_export() function rather than print_r.
As described here by phihad
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script
the script:
$json = '{"main":{"title": "QuickPub","defaultRole": "BU"},"roles":{"TU":{"name": "testUser","code": "TU"}}}';
$array = json_decode($json, 1);
$result = var_export($array, 1);
echo $result;
produces:
array(
'main' => array(
'title' => 'QuickPub',
'defaultRole' => 'BU',
),
'roles' => array(
'TU' => array(
'name' => 'testUser',
'code' => 'TU',
),
),
)
This can be achieved using this code:
$output = 'return ' . rtrim(preg_replace(['/{/', '/}/', '/:/'], ['[', ']', ' =>'], $json)) . ';';
this replaces { with [, } with ], and : with =>, trims any whitespace from the end, appends a ; and prepends a return statement.
this produces the output requested in the question bar the open and closing php tags.
I have a PHP script and want to write that in Python. So,
How can I convert this nested PHP Array to nested python dictionary?
$data = [
'details'=> [
[
['quick_event'=> 'Quick'],
['advance_event'=> 'Advanced']
],
[
['help'=> 'Help']
]
],
'has_car'=> true,
'has_payment'=> false
];
I created this in Python but it's wrong:
data = {
'details': {
{
{'quick_event': 'Quick'},
{'advance_event': 'Advanced'}
},
{
{'help': 'Help'}
}
},
'has_car': True,
'has_payment': False
}
This question is rather narrow but here we go:
data = {
'details': [
[
{'quick_event': 'Quick'},
{'advance_event': 'Advanced'}
],
[
{'help': 'Help'}
]
],
'has_car': True,
'has_payment': False
};
>>> data
{'details': [[{'quick_event': 'Quick'}, {'advance_event': 'Advanced'}], [{'help': 'Help'}]], 'has_car': True, 'has_payment': False}
In a nutshell:
Convert => to :
Convert [] to {} for maps.
In php use http://php.net/manual/en/function.json-encode.php to format the data as json.
In python convert the json to a dictionary.
Maybe check this link to see how to convert json to dictionary in python:
Converting JSON String to Dictionary Not List
$array = array(
$this->_order->revenue_seller($value,$from,$to),
$this->_order->refund_seller($value,$from,$to),
$this->_order->customers_seller($value,$from,$to),
$this->_order->sales_seller($value,$from,$to)
);
$this->response($array,200);
I want the data to be be displayed as a single array, but as we can see, the output is begin displayed as array of arrays:
[
[
{
"min_amount":"2.00",
"max_amount":"2.00",
"avg_amount":"2.000000",
"total_revenue":"2.00"
}
],
[
{
"total_refund_amount":"1.00"
}
],
[
{
"created_at":"2013-03-24 15:04:35"
}
],
[
{
"quantity":"1"
}
]
]
How can I make the data appear as one single array?
Like this:
[
{
"day":"2013-03-19",
"min_amount":"0.00",
"max_amount":"0.00",
"avg_amount":"0.000000",
"total_revenue":"0.00",
"quantity" : "1",
"total_refunded_amount":null,
"created_at":"2013-03-24 15:04:35"
}]
If you are getting array return by all four function than use array_merge as,
$array = array_merge($this->_order->revenue_seller($value,$from,$to),
$this->_order-refund_seller($value,$from,$to),
$this->_order->customers_seller($value,$from,$to),
$this-_order->sales_seller($value,$from,$to));
$this->response($array,200);
DEMO.