creating valid json data in Laravel - php

When a new User is created, I save the username and password (no hashed) in a json file as well as in the DB, so every time I'm appending new users to the json file:
{
"user3": "demo"
} {
"user4": "demo"
} {
"user4": "demo"
} {
"user5": "demo"
}
the code:
$data = array($request->input('username') => $request->input('password'));
$datos = json_encode($data);
File::append(storage_path('archivos/datos.json'), $data);
of course the format above isn't valid json, how could i get this
[{
"user3": "demo"
}, {
"user4": "demo"
}, {
"user4": "demo"
}, {
"user5": "demo"
}, {
"user5": "demo"
}, {
"user5": "demo"
}, {
"user7": "demo"
}, {
"user8": "demo"
}]
and read it using foreach like this:
$result = File::get(storage_path('archivos/datos.json'));
$result = json_decode($result);
foreach($result as $key=>$item){
echo $key .''. $item;
}

First get the string from file then you can do a str_replace all "} {" with "} , {" a json also have [ at the start and ] at the end so we add them too:
$json = "[".str_replace('} {', '},{', $fileContent)."]";
Here we have a json string in $json variable so we can convert it to array by this:
$users = json_decode($json);

the fastest way would be to append some data:
fopen('myfile.json', 'a');
but you want to store an array, so you have to read the content of the file, update it and save it.
$users = json_decode(file_get_content(storage_path('archivos/datos.json')));
$users[] = $newUser;
file_put_contents(storage_path('archivos/datos.json'), json_encode($users, JSON_PRETTY_PRINT);
you can also make a one-liner (ugly, but works):
file_put_contents(storage_path('archivos/datos.json'), json_encode(json_decode(file_get_content(storage_path('archivos/datos.json')))[] = $newUser, JSON_PRETTY_PRINT);

Related

How to correctly create and append data in a JSON Object using PHP?

I'm struggling on how to properly create a JSON file and append data to it, here's my PHP code:
<?php
$jsonFile = "_users.json";
$username = $_GET["username"];
$email = $_GET["email"];
$objID = $_GET["objID"];
//Load the file
$jsonStr = file_get_contents($jsonFile);
//Decode the JSON data into a PHP array.
$array = json_decode($jsonStr, true);
if ($array != null) {
$arrNew['ObjID']++;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
} else {
$arrNew = [];
$array['ObjID'] = 0;
$array['username'] = $username;
$array['email'] = $email;
array_push($array, $arrNew);
}
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($array);
file_put_contents($jsonFile, $jsonData);
// echo data
echo $jsonData;
?>
If I refresh the URL in my browser by calling my php file, I get this output if i go to example.com/_users.json
{
"0": [],
"1": {
"ObjID": 1,
"username": "bob",
"email": "b#doe.com"
},
"2": {
"ObjID": 1,
"username": "sarah",
"email": "b#doe.com"
},
"3": {
"ObjID": 1,
"username": "sarah",
"email": "b#doe.com"
},
"ObjID": 0,
"username": "bob",
"email": "b#doe.com"
}
So I'm able to generate a .json file, but what I need to do is a piece of code to do the following sequence:
Since the first time I run the script, the _users.json file doesn't exist, it needs to get generated
Create a JSON main object
Insert 1st object inside the main object
Append a 2nd object (still inside the main object)
And so on with 3rd, 4th, etc..
So I would need to get an output like this:
{ <-- Main Object starts
"1": { <-- 1st object inside the Main Object
"ObjID": 1,
"username": "bob",
"email": "b#doe.com"
},
"2": { <-- 2nd object
"ObjID": 1,
"username": "sarah",
"email": "s#doe.com"
}
} <-- Main Object closes
I can't really figure out what I'm doing wrong in my PHP code.
Logic in the else part should be inverted:
} else {
$array = [];
$arrNew['ObjID'] = 0;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
}
Try below code.
$jsonFile = "_users.json";
$username = $_GET["username"];
$email = $_GET["email"];
$objID = $_GET["objID"];
//Load the file
$jsonStr = file_get_contents($jsonFile);
//Decode the JSON data into a PHP array.
if($jsonStr=='') $array = array();
else $array = json_decode($jsonStr, true);
if (empty($array)) {
$arrNew = [];
$arrNew['ObjID']=0;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
} else {
$array['ObjID'] ++;
$array['username'] = $username;
$array['email'] = $email;
array_push($array, $arrNew);
}
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($array);
file_put_contents($jsonFile, $jsonData);
// echo data
echo $jsonData;
?>

Parse Nested JSON with PHP

I've look high and low for a solution for this, but haven't found anything that is exactly what I am running into. I am using php to parse a JSON response that is nested in a way that makes it difficult to extract specific fields.
Here is a bit of the JSON:
{
"collection":{
"items":[
{
"href":"https://api.teamsnap.com/v3/members/MEMBERID",
"data":[
"name":"id",
"value": 0000000 // MEMBERID
},
{
"name":"type",
"value":"member"
},
{
"name":"address_city",
"value":""
},
{
"name":"address_state",
"value":""
},
Here is my php:
$json = file_get_contents($url, false, $context);
$result = json_decode($json);
foreach ($result->collection->items as $items=>$val) {
foreach ($val->data as $data=>$datasets) {
foreach ($datasets as $dataset=>$val) {
echo $dataset.': '.$val;
echo "<br>";
}
}
};
and this is a bit of the current output:
name: id
value: MEMBERID
name: first_name
value: MEMBERNAME
name: last_name
value: MEMBERNAME
what I want to do is be able to list all of the members in this response with their first and last name. I have tried using $val->first_name, $val['first_name']; and such but all result in a foreach error.
If you can ensure every data member has a name and value field you can use something like this and skip a for-loop:
$json = file_get_contents($url, false, $context);
$result = json_decode($json);
foreach ($result->collection->items as $itemKey => $val) {
$data = array();
foreach ($val->data as $dataKey => $dataset) {
$data[$dataset->name] = $dataset->value;
}
var_dump($data);
};
Although you should probably check for $result->collection and $result->collection->items first before looping over them to avoid errors.

Remove Value from JSON PHP

I am new to PHP and I am working on wordpress JSON api. I want to remove Key:value pair inside a JSON array. Please help
{
"status":"ok",
"post":{
"id":23,
"type":"post",
"slug":"head-ache",
"url":"http:\/\/xyz.com\/maruthuvam\/2015\/06\/17\/head-ache\/",
"status":"publish",
"title":"Head Ache",
"title_plain":"Head Ache",
"content":"<p>content<\/p>\n<p> <\/p>\n",
"excerpt":"<p>content <\/p>\n",
"date":"2015-06-17 19:35:47",
"modified":"2015-06-18 07:35:39",
"categories":[
{
"id":1,
"slug":"head",
"title":"Head",
"description":"http:\/\/xyz.com\/maruthuvam\/wp-content\/uploads\/2015\/06\/universa_-male_head_3d_model_01.jpg",
"parent":0,
"post_count":3
}
],
"tags":[
],
"author":{
"id":1,
"slug":"admin",
"name":"admin",
"first_name":"",
"last_name":"",
"nickname":"admin",
"url":"",
"description":""
},
"comments":[
],
"attachments":[
],
"comment_count":0,
"comment_status":"closed",
"custom_fields":{
}
},
"next_url":"http:\/\/xyz.com\/maruthuvam\/2015\/06\/17\/head- lice\/"
}
For example I want to remove "slug":"head-ache" from "post" and "post_count":0, from "categories" and "next-url". Please help.
UPDATE::
I have added the code in core.php and its not working. Can you please help me out.
public function get_post() {
global $json_api, $post;
$post = $json_api->introspector->get_current_post();
if ($post) {
$previous = get_adjacent_post(false, '', true);
$next = get_adjacent_post(false, '', false);
$response = array(
'post' => new JSON_API_Post($post)
);
if ($previous) {
$response['previous_url'] = get_permalink($previous->ID);
}
if ($next) {
$response['next_url'] = get_permalink($next->ID);
}
// parsing json
$arr = decode_json($response);
// removing the value
unset($arr['post']['slug']);
// and back to json
$response = json_encode($arr);
return $response;
} else {
$json_api->error("Not found.");
}
}
Just convert it to a PHP Array:
$jsonArray = json_decode($jsonString);
Remove the Keys
unset($jsonArray['post']['slug']);
And convert back:
$newJson = json_encode($jsonArray);
You need to parse it to ordinary array, then remove what you want and encode it back to json:
// parsing json
$arr = decode_json($yourJson);
// removing the value
unset($arr['post']['slug']);
// and back to json
$editedJson = json_encode($arr);
$a= json_decode($data,true);
unset($a['post']['slug']);
unset($a['next_url']);
$count= count($a['post']['categories']);
for($i=0 ; $i < $count ; $i++){
unset($a['post']['categories'][$i]['post_count']);
}
echo json_encode($a);

Overwrite a json after modification in PHP

I make a modification in my json with this code:
$id = "hotel_name";
$value ="My Hotel";
$json = json_decode(file_get_contents('datas.json'));
$datas = $json->datas;
foreach ($datas as $category => $data) {
foreach ($data as $element) {
if($element->id==$id) {
$datas->$category->$element->$id = $value;
}
}
}
$newJson = json_encode($element);
file_put_contents('datas.json', $newJson);
But it do not put all the content in it.
How to solve it please ?
My json has the following:
{
"datas": {
"General": [
{
"field": "hotel_name",
"name": "My Hotel name"
}
]
}
}
You are accessing the $element variable, which contains only your inner most data
{
"field": "hotel_name",
"name": "My Hotel name"
}
If you want more of your data, you will have to reassign your outermost $datas variable and children with the newly updated $element variable. I'd recommend creating an empty variable to store the new data instead of altering the original copy.
You should be encoding datas, not just the last element, right?
// before
$newJson = json_encode($element);
// after
$newJson = json_encode($datas);
By the way, you might find it easier to work with the data if you convert it to an array rather than object.
$json = json_decode(file_get_contents('datas.json'), true);

Fetch json data using PHP

I have a json file and I want to display it data using PHP. My below code gives me error,
$json = file_get_contents('data.json');
$data = json_decode($json,true);
$users = $data['devices'];
foreach($users as $user)
{
echo $user['id'];
echo $user['user'];
}
When I replace the 3rd LOC with $users = $data['user']; then it display some data with single alphabet i don't know in which order.
Data.json file contains the following data
{
"user":
{
"id":"#03B7F72C1A522631",
"user":"test#mail.com",
"password":"123",
"email":"test#mail.com",
"name":"m",
"creationDate":1385048478,
"compression":true,
"imageProfile":"medium",
"videoProfile":"medium",
"blockAdvert":true,
"blockTracking":true,
"devices":[
{
"id":"#13C73379A7CC2310",
"udid":"cGMtd2luNi4xLV",
"user":"test#mail.com",
"creationDate":1385048478,
"status":"active",
},
{
"id":"#FE729556EDD9910D",
"udid":"C1N1",
"user":"test#mail.com",
"creationDate":1385291938,
"status":"active",
}]
},
"status":
{
"version":"0.9.5.0",
"command":"getuser",
"opf":"json",
"error":false,
"code":0
}
}
I believe you skipped 1 node, try:
$users = $data['user']['devices'];
This should work;
$json = file_get_contents('data.json');
$data = json_decode($json,true);
$users = $data['user']['devices'];
foreach($users as $user) {
echo $user['id'];
echo $user['user'];
}
There is one key before 'devices'.
I think you may want do display all the devices info, you can change you code to:
$json = file_get_contents('data.json');
$data = json_decode($json,true);
// change the variable name to devices which is clearer.
$devices = $data['user']['devices'];
foreach ($devices as $device)
{
echo $device['id'];
echo $device['user'];
}
You are not accessing your json correctly. You need to access it like this.
$yourVariable = $data['users']['devices'];
Try that.

Categories