" " instead of [ ] in JSON - javascript

I used a php variable into Javascript like this-
var Coordinates = <?php echo json_encode($coords); ?>;
And now I want to stringify it so I used
var JSON_Coordinates = JSON.stringify(Coordinates);
the result is
["-98.47442960102632,38.51861967935271","-98.46128420909388,38.17510666712973","-97.91584295178713,38.17274814619617", -"97.91882439611877,38.51683243137235", "-98.47442960102632,38.51861967935271"]
But I want It to be like this-
[[-98.47442960102632,38.51861967935271],[-98.46128420909388,38.17510666712973],[-97.91584295178713,38.17274814619617], [-97.91882439611877,38.51683243137235], [-98.47442960102632,38.51861967935271]]
So how to replace " " with [ ]?

You could fix it on the server side:
$coords = array(
'-98.47442960102632,38.51861967935271',
'-98.46128420909388,38.17510666712973',
'-97.91584295178713,38.17274814619617',
'-97.91882439611877,38.51683243137235',
'-98.47442960102632,38.51861967935271'
);
$coords = array_map(function($coord) {
list($lat, $lon) = explode(",", $coord);
return array((float) $lat, (float) $lon);
}, $coords);
echo json_encode($coords);
Output (pretty printed):
[
[-98.474429601026, 38.518619679353],
[-98.461284209094, 38.17510666713],
[-97.915842951787, 38.172748146196],
[-97.918824396119, 38.516832431372],
[-98.474429601026, 38.518619679353]
]

Before converting to json in php, you could convert each coords string to an array in a loop, then ensure values are not strings but numeric using JSON_NUMERIC_CHECK
<?php
foreach ($coords as &$value) {
$value = explode(',', $value); // prevent to array like ["23","45"]
}
unset($value); // avoid reuse of &reference variable by mistake
echo json_encode($coords, JSON_NUMERIC_CHECK);
?>

Related

How do I parse this json data in view laravel [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 9 months ago.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
I tried to parse a JSON file using PHP. But I am stuck now.
This is the content of my JSON file:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
And this is what I have tried so far:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
echo $json_a['John'][status];
echo $json_a['Jennifer'][status];
But because I don't know the names (like 'John', 'Jennifer') and all available keys and values (like 'age', 'count') beforehand, I think I need to create some foreach loop.
I would appreciate an example for this.
To iterate over a multidimensional array, you can use RecursiveArrayIterator
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Output:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
run on codepad
I can't believe so many people are posting answers without reading the JSON properly.
If you foreach iterate $json_a alone, you have an object of objects. Even if you pass in true as the second parameter, you have a two-dimensional array. If you're looping through the first dimension you can't just echo the second dimension like that. So this is wrong:
foreach ($json_a as $k => $v) {
echo $k, ' : ', $v;
}
To echo the statuses of each person, try this:
<?php
$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
// deal with error...
}
$json_a = json_decode($string, true);
if ($json_a === null) {
// deal with error...
}
foreach ($json_a as $person_name => $person_a) {
echo $person_a['status'];
}
?>
The most elegant solution:
$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);
Remember that the json-file has to be encoded in UTF-8 without BOM. If the file has BOM, then json_decode will return NULL.
Alternatively:
$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;
Try
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);
foreach ($json_a as $key => $value){
echo $key . ':' . $value;
}
?>
It's completely beyond me that no one pointed out that your begining "tags" are wrong. You're creating an object with {}, while you could create an array with [].
[ // <-- Note that I changed this
{
"name" : "john", // And moved the name here.
"status":"Wait"
},
{
"name" : "Jennifer",
"status":"Active"
},
{
"name" : "James",
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
] // <-- And this.
With this change, the json will be parsed as an array instead of an object. And with that array, you can do whatever you want, like loops etc.
Try This
$json_data = '{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}';
$decode_data = json_decode($json_data);
foreach($decode_data as $key=>$value){
print_r($value);
}
Try:
$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br />';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br />';
}
}
}
More standard answer:
$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val):
echo '<b>Name: '.$k.'</b></br>';
$keys = array_keys($val);
foreach($keys as $key):
echo ' '.ucfirst($key).' = '.$val[$key].'</br>';
endforeach;
endforeach;
And the output is:
Name: John
Status = Wait
Name: Jennifer
Status = Active
Name: James
Status = Active
Age = 56
Count = 10
Progress = 0.0029857
Bad = 0
Loop through the JSON with a foreach loop as key-value pairs. Do type-checking to determine if more looping needs to be done.
foreach($json_a as $key => $value) {
echo $key;
if (gettype($value) == "object") {
foreach ($value as $key => $value) {
# and so on
}
}
}
<?php
$json = '{
"response": {
"data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
"status": 0,
"totalRows": 83,
"startRow": 0,
"endRow": 82
}
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status'];
echo $json['response']['totalRows'];
echo $json['response']['startRow'];
echo $json['response']['endRow'];
?>
Try it:
foreach ($json_a as $key => $value)
{
echo $key, ' : ';
foreach($value as $v)
{
echo $v." ";
}
}
When you decode a json string, you will get an object. not an array. So the best way to see the structure you are getting, is to make a var_dump of the decode. (this var_dump can help you understand the structure, mainly in complex cases).
<?php
$json = file_get_contents('/home/michael/test.json');
$json_a = json_decode($json);
var_dump($json_a); // just to see the structure. It will help you for future cases
echo "\n";
foreach($json_a as $row){
echo $row->status;
echo "\n";
}
?>
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
foreach($json_a as $person => $value)
{
foreach($value as $key => $personal)
{
echo $person. " with ".$key . " is ".$personal;
echo "<br>";
}
}
The quickest way to echo all json values is using loop in loop, the first loop is going to get all the objects and the second one the values...
foreach($data as $object) {
foreach($object as $value) {
echo $value;
}
}
You have to give like this:
echo $json_a['John']['status'];
echo "<>"
echo $json_a['Jennifer']['status'];
br inside <>
Which gives the result :
wait
active
I am using below code for converting json to array in PHP,
If JSON is valid then json_decode() works well, and will return an array,
But in case of malformed JSON It will return NULL,
<?php
function jsonDecode1($json){
$arr = json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
?>
If in case of malformed JSON, you are expecting only array, then you can use this function,
<?php
function jsonDecode2($json){
$arr = (array) json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
?>
If in case of malformed JSON, you want to stop code execution, then you can use this function,
<?php
function jsonDecode3($json){
$arr = (array) json_decode($json, true);
if(empty(json_last_error())){
return $arr;
}
else{
throw new ErrorException( json_last_error_msg() );
}
}
// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
?>

Get a php array into a js array

I want to get a php array made by pg_fetch_all in a javascript array. But when I try to do it, firebug tells me that I'm trying to convert an array to string. Indeed, I don't understand why because both are arrays.
Here is where I create the php array :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT ".$colonne." FROM public.".$tablevar."";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$data = pg_fetch_all($res);
And here is my js code :
var array_dropdown =[<?php echo $data;?>];
And it doesn't work. Please help me !
PHP Arrays 101: Arrays in a string context are the literal word Array:
$x = array(1 => 2);
echo $x; // ouputs "Array"
You need to use json_encode():
var array_dropdown = <?php echo json_encode($data); ?>;
json_encode guarantees that whatever you pass in to the encode function will be output as syntactically valid javascript. Note the lack of [] around the above code - json_encode handles all of that for you.
Assume this as your PHP array
$array = array('foo' => 'bar');
The JS part:
var array = <?php echo json_encode($array); ?>;

Combine a string and an array with JSON

I'm trying to combine a string and an array with JSON. No success, so far.
Here is the PHP code:
<?php
$url = ‘example.com’;
$data = file_get_contents($url);
$regex = '/list-animal-id">(.+?)</';
$input = ‘testtext';
preg_match_all($regex,$data, $match);
//var_dump($match);
//echo json_encode($match[1]);
$json = array($input, $match[1]);
$json_data = json_encode($json);
echo $json_data;
?>
$match comes back with an array, for instance:
"22425229","22493325","22596308","24635614","22202322"
The above only creates one instance of the string:
["testtext",["22425229","22493325","22596308"......
I want to create something like this:
"testtext":"22425229", "testtext":"22425230"
Thanks,
What you are looking to do is not possible. [ "testtext":"22425229", "testtext":"22425230" ] assumes an array in which every key is "testtext". You cannot have an array or object with the same key repeated.
What you can do is create an array of arrays where each item is an associative array (object in JSON):
<?php
$url = 'example.com';
$data = file_get_contents($url);
$regex = '/list-animal-id">(.+?)</';
$input = 'testtext';
preg_match_all($regex,$data, $match);
//var_dump($match);
//echo json_encode($match[1]);
function outputArray( $value ) {
global $input;
return array( $input => $value );
}
$json = array_map( 'outputArray', $match );
$json_data = json_encode($json);
echo $json_data;
?>
Output is: [{"testtext":"22425229"},{"testtext":"22493325"},{"testtext":"22596308"},{"testtext":"24635614"},{"testtext":"22202322"}]
my solution was wrong and shouldn't stay here confusing others... the right solution can be found in Jims answere...

How can get values from php array using jquery or javascript?

I trying to get data from php array and put in java-script variable. Follwoing are the php arrays.
Array Name
Array
(
[0] => username
[1] => byusers
)
Array Value
Array
(
[0] => user
[1] => 1
)
What I have Try tried
Get php array value in javascript variable
var DATATABLE_SEARCH_NAMES = new Array( "<?php echo (is_array($DATATABLE_SEARCH_DATA_NAMES)) ? $DATATABLE_SEARCH_DATA_NAMES['names'] : 0;?>");
var DATATABLE_SEARCH_VALUES = new Array( "<?php echo (is_array($DATATABLE_SEARCH_DATA_VALUE)) ? $DATATABLE_SEARCH_DATA_VALUE['values'] : 0;?>");
This should do what you ask, it is just a case of converting the PHP arrays to a form that javascript can understand. You can use json_encode() to do that.
$DATATABLE_SEARCH_DATA_NAMES = array('username','byusers');
$DATATABLE_SEARCH_DATA_VALUE = array('user', 1);
$js1 = json_encode($DATATABLE_SEARCH_DATA_NAMES);
$js2 = json_encode($DATATABLE_SEARCH_DATA_VALUE);
//echo $js1.PHP_EOL;
//echo $js2.PHP_EOL;
echo "<script>\n";
echo 'var names = ' . $js1 . ";\n";
echo 'var values = ' . $js2 . ";\n";
echo "</script>\n";
say, you have a PHP array as this:
$arr = array("key1"=>"foo","key2"=>"bar");
the easiest way to put it to javascript is this:
var arr = <?php echo json_encode($arr); ?>;
ending with a JSON object.

How to create javascript array from database by php

I want to create a javascript array from databse like this:
var m = [
[one]
[two]
[three]
]
it is important that typeof m be object.
Use Json_encode
$phparray; // This is your php array
$jsArray = <?php echo json_encode($phparray); ?>;
//do stuff with $jsArray now

Categories

Resources