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

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) );
?>

Related

" " instead of [ ] in JSON

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);
?>

Cannot get value from Key JSON MySQL PHP

I am retrieving data from a MySQL database using PHP and attempting to use JSON.stringify and JSON.parse to create an object. It works fine but I cannot get the assocaited keys/values. Just the entire object. I break this up in to parts. Here is the PHP code:
First PHP File:
<?php
session_start();
include("web_db_operations.php");
if(isset($_POST['recipeId']) && isset($_SESSION['email'])){
$recipeId = $_POST['recipeId'];
$email = $_SESSION['email'];
}
else{
echo "Did not work";
}
$results = getAllMyRecipesAsList_recipeTable2($email, $recipeId);
$_SESSION['recipeResults'] = $results;
header('location:web_selected_recipe.php');
exit();
?>
Second PHP File
function getAllMyRecipesAsList_recipeTable2(string $email, int $recipeId){
include 'config.php';
$sql = 'SELECT * FROM recipeTable WHERE email = :email AND recipeId = :recipeId';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':recipeId', $recipeId, PDO::PARAM_STR);
$stmt->execute();
$getResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
$json = array();
if(count($getResults) > 0){
foreach($getResults as $row){
$json[] = array('firstName' => $row['firstName'],
'lastName' => $row['lastName'],
'email' => $row['email'],
'recipeName' => $row['recipeName'],
'description' => $row['description'],
'ingredients' => $row['ingredients'],
'prepTime' => $row['prepTime'],
'steps' => $row['steps'],
'nutrition' => $row['nutrition'],
'servings' => $row['servings'],
'rating' => $row['rating'],
'tags' => $row['tags'],
'imagePath' => $row['imagePath'],
'imageName' => $row['imageName'],
'recipeId' => $row['recipeId']
);
}
$results = json_encode($json);
return $results;
}else{
echo "no data found";
}
}
Then to retrieve in my JS file (this is just the relevant parts):
<script>
<?php $results = $_SESSION['recipeResults'];
var results = <?php echo $results; ?>;
var toString = JSON.stringify(results);
console.log(toString);
var parsed = JSON.parse(toString);
console.log(parsed);
</script>
Logging resultAsString yields this:
[{"firstName":"Marcus","lastName":"Holden","email":"marcus#gmail.com","recipeName":"Aloo Paratha","description":"","ingredients":"","prepTime":"25 Minutes","steps":"","nutrition":"","servings":"","rating":"","tags":"","imagePath":"../userRecipeImages","imageName":"9110164.jpg","recipeId":"1"}]
Logging parsed yields this:
[{…}]
0:description:
"No Description", email "marcus#gmail.com", firstName:"Marcus", imageName:"9110164.jpg", imagePath:"../userRecipeImages", ingredients:"Some Ingredients",lastName:"Holden", nutrition:"Not given", prepTime:"25 Minutes", rating:"5/10", recipeId:"1", recipeName:"Aloo Paratha", servings: "6", steps:"Your Steps Here", tags:"It's bread"
Now, I have tried all steps to get the value associated with a key... for instance my object here is called parsed... so I have tried parsed.firstName.. returns undefined... as well as Object.keys(parsed). I cannot seem to get the keys. I would like to work with it like an array... setting content like this:
element.innerHTML = parsed[2]... etc.
What am I missing here?
I think you're doing quite a bit more than you need to. The data is coming to you as a JSON-encoded object. Just work with it.
<script>
var results = <?php echo $_SESSION['recipeResults']; ?>;
var first_results = results[0]; // Each array member is one object from your result set
console.log( first_results.firstName );
console.log( results[0].firstName ); // OR specify which array index to interact directly
</script>

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.

Parsing JSON file to produce and return another JSON with required data

I need to parse a given JSON file for events that occur between the start and end time that are passed through an HTTP GET. The events that occur between this range should then be returned as a new JSON encoded response. So far I have come up with two possible solutions. Neither seem to be giving me the expected JSON encoded file.
EDIT: Aside from the script not producing the proper JSON file, I get the following error in the developers console on Chrome: Uncaught TypeError: Cannot read property 'length' of null
Solution 1:
$param1 = $_GET['startTime'];
$param2 = $_GET['endTime'];
$data = file_get_contents('./events.json');
$json = json_decode($data, true);
foreach ($json as $key => $value){
if ($value > $param1 && $value < $param2) {
echo "$key => $value"; }
else { return; }
}
Solution 2 (same parameters passed in, different for each loop):
foreach ($json as $key => $value){
if ($value >= $param1 && $value <= $param2) {
$tempFile = "tempEvents.json";
$jsonArray = json_decode(file_get_contents($tempFile), true);
array_push($jsonArray, array( 'title' => ????, 'start' => $param1, 'end' => $param2 ));
file_put_contents($file, json_encode($jsonArray));
}
else { return; }
echo json_encode('tempEvents.json');
}
Sample JSON file to be parsed:
[
{
"Name":"Event 1",
"Start Time":258147369,
"End Time":369147258
},
{
"Name":"Event 2",
"Start Time":789456123,
"End Time":159487263
},
]
You should use json_encode on an array to get well-formed JSON output. I can't speak for your if statement's validity as you haven't provided any sample data, but this is how you should do your conversion:
$param1 = $_GET['startTime'];
$param2 = $_GET['endTime'];
$data = file_get_contents('./events.json');
$json = json_decode($data, true);
$output = array();
foreach ($json as $key => $value){
if ($value > $param1 && $value < $param2)
$output[$key] = $value;
}
$json_out = json_encode($output);
echo $json_out; // this outputs to the browser
// to output to file, use $json_out as your string to write to file

Categories

Resources