Applying condition on dynamically extract keys to construct sample json response
Applying condition on dynamically extract keys-value pair to construct sample json response with key-value pair
Applying condition on dynamically extract keys to construct sample json response
my request data is
Log::info('Data received via AJAX:', $request->all());
Data received via AJAX: {"_token":"JEQba4vUNZ5LP1Jz7eaI9JAwblbOAf7S8EO6i14C","admin_id":"26","slug":"admins","influencer_email":"admins@gmail.com","admin_email":"rakeshdev.cotocus@gmail.com","user_name":"rakeshdev","item":"25","dataitem_id":"25","selected_socials":"face_price,youtube_price"}
after getting data from table
$payments=payments::where('admin_id',$addprofile->user_id)->first();
Log::info($payments);
{"id":82,"User_id":null,"admin_id":28,"users_name":"admins","slug":null,"admin_email":"admins@gmail.com","face_price":"24","twitter_price":null,"youtube_price":"69","wordpress_price":null,"tumblr_price":null,"instagram_price":null,"quora_price":null,"pinterest_price":null,"reddit_price":null,"koo_price":null,"scoopit_price":null,"slashdot_price":null,"fb_grp_price":null,"telegram_price":null,"linkedin_grp_price":null,"linkedin_price":null,"roposo_price":null,"chingari_price":null,"mitron_price":null,"created_at":"2024-01-04T04:51:39.000000Z","updated_at":"2024-01-04T04:51:39.000000Z"}
I want to extract request data from $ payment and i have to apply condition price value is not null where suffix is _price and put in json response
step1: extract request key from $payments and put inside array $priceData
$priceData = [];
foreach ($payments as $key => $value) {
// Check if the key contains "_price" and the value is not null
if (strpos($key, '_price') !== false && $value !== null) {
$priceData[$key] = $value;
}
}
In Django
# views.py
from django.shortcuts import render
from .models import Payments
import logging
def your_view(request):
add_profile = # Retrieve the addprofile instance, it's not provided in your code snippet
payments = Payments.objects.filter(admin_id=add_profile.user_id).first()
logging.info(payments)
price_data = {}
if payments:
payments_dict = payments.__dict__
for key, value in payments_dict.items():
# Check if the key contains "_price" and the value is not None
if '_price' in key and value is not None:
price_data[key] = value
response_data = {
'message': 'task disapprove successfully',
'success': True,
'prices': price_data,
'influencer': request.GET.get('slug', ''), # Assuming slug is sent via query parameters
'publisher': request.GET.get('user_name', ''), # Assuming user_name is sent via query parameters
}
return JsonResponse(response_data)
using context
# views.py
from django.shortcuts import render
from .models import Payments
import logging
def your_view(request):
add_profile = # Retrieve the addprofile instance, it's not provided in your code snippet
payments = Payments.objects.filter(admin_id=add_profile.user_id).first()
logging.info(payments)
price_data = {}
if payments:
payments_dict = payments.__dict__
for key, value in payments_dict.items():
# Check if the key contains "_price" and the value is not None
if '_price' in key and value is not None:
price_data[key] = value
context = {
'price_data': price_data,
}
return render(request, 'your_template.html', context)
In template
{% if price_data %}
{% for key, value in price_data.items %}
{# Check if the key contains "_price" and the value is not null #}
{% if "_price" in key and value %}
{# Process the key and value as needed #}
<p>{{ key }}: {{ value }}</p>
{% endif %}
{% endfor %}
{% else %}
{# Handle the case when price_data is empty or None #}
{% endif %}
step2: next step to construct json response
return response()->json([
'message' => "task disapprove successfully",
'success' => true,
'prices' => $priceData,
'influencer' =>$request->slug,
'publisher' =>$request->user_name,
]);
output
{
"message": "Task disapproved successfully",
"success": true,
"prices": {
"face_price": "24",
"youtube_price": "69"
},
"influencer": "sample-influencer",
"publisher": "sample-publisher"
}
Applying condition on dynamically extract keys-value pair to construct sample json response with key-value pair
my data is
$myaddcarts=addcart::where('influencer_admin_id',$addprofile->user_id)->first();
Log::info($myaddcarts)
;
{"id":78,"admin_id":"26","cart_id":"CART-yRYT-26","paid":"no","influencer_admin_id":29,"admin_email":"rakeshdev.cotocus@gmail.com","user_name":"rakeshdev","slug":"rikogo3000","influencer_email":"raj@gmail.com","org_name":null,"twitter_price":"60","youtube_price":"67","face_price":"34","wordpress_price":null,"tumblr_price":null,"instagram_price":null,"quora_price":null,"reddit_price":null,"koo_price":null,"scoopit_price":null,"slashdot_price":null,"fb_grp_price":null,"linkedin_grp_price":null,"telegram_price":null,"linkedin_price":null,"roposo_price":null,"chingari_price":null,"mitron_price":null,"pinterest_price":null,"created_at":"2024-01-06T07:19:16.000000Z","updated_at":"2024-01-06T07:19:16.000000Z"}
I want to extract request data from $ payment and i have to apply condition price value is not null where suffix is _price and put in json response
step1: extract request key from $payments and put inside array $priceData
This loop iterates through each key-value pair in the $paymentsArray. It checks if the key contains "_price" and the corresponding value is not null. If both conditions are met, it extracts the social site name from the key (by removing "_price") and adds an associative array with the social site name and the price to the $priceData['prices'] array. Additionally, it logs the price data using Laravel's Log::info method.
if ($myaddcarts) {
$paymentsArray = $myaddcarts->toArray();
foreach ($paymentsArray as $key => $value) {
// Check if the key contains "_price" and the value is not null
if (strpos($key, '_price') !== false && $value !== null) {
$socialSite = str_replace('_price', '', $key);
// Add the social site and price as an associative array to $priceData
$priceData['prices'][] = ['social_site' => $socialSite, 'price' => $value];
Log::info('Price data:', $priceData['prices']);
}
}
}
if (!empty($priceData)) {
Log::info('Price data is present:', $priceData);
} else {
Log::info('No price data found');
}
step2: next step to construct json response
return response()->json([
'message' => "task disapprove successfully",
'success' => true,
'prices' => $priceData,
'influencer' =>$request->slug,
'publisher' =>$request->user_name,
]);
output
display json key value pair
{
"message": "Task disapproved successfully",
"success": true,
"prices": [
{"social_site": "face", "price": "60"},
{"social_site": "youtube", "price": "67"}
{"social_site":"face","price":"34"}
],
"influencer": "rajesh ",
"publisher": "rakeshdev"
}
Applying condition on dynamically extract keys-value pair to construct sample json response with key-value pair in Django
my data is
models.py
from django.db import models
from django.contrib.auth.models import User
class AddCart(models.Model):
influencer_admin_id = models.ForeignKey(User, on_delete=models.CASCADE)
# other fields...
views.py
from django.shortcuts import render
from .models import AddCart
def your_view(request):
add_profile = # Retrieve the addprofile instance, it's not provided in your code snippet
my_add_carts = AddCart.objects.filter(influencer_admin_id=add_profile.user_id).first()
{"id":78,"admin_id":"26","cart_id":"CART-yRYT-26","paid":"no","influencer_admin_id":29,"admin_email":"rakeshdev.cotocus@gmail.com","user_name":"rakeshdev","slug":"rikogo3000","influencer_email":"raj@gmail.com","org_name":null,"twitter_price":"60","youtube_price":"67","face_price":"34","wordpress_price":null,"tumblr_price":null,"instagram_price":null,"quora_price":null,"reddit_price":null,"koo_price":null,"scoopit_price":null,"slashdot_price":null,"fb_grp_price":null,"linkedin_grp_price":null,"telegram_price":null,"linkedin_price":null,"roposo_price":null,"chingari_price":null,"mitron_price":null,"pinterest_price":null,"created_at":"2024-01-06T07:19:16.000000Z","updated_at":"2024-01-06T07:19:16.000000Z"}
I want to extract request data from $ payment and i have to apply condition price value is not null where suffix is _price and put in json response
step1: extract request key from $payments and put inside array $priceData
This loop iterates through each key-value pair in the $paymentsArray. It checks if the key contains "_price" and the corresponding value is not null. If both conditions are met, it extracts the social site name from the key (by removing "_price") and adds an associative array with the social site name and the price to the $priceData['prices'] array. Additionally, it logs the price data using Laravel's Log::info method.
price_data = {'prices': []}
if my_add_carts:
payments_dict = my_add_carts.__dict__
for key, value in payments_dict.items():
# Check if the key contains "_price" and the value is not None
if '_price' in key and value is not None:
social_site = key.replace('_price', '')
# Add the social site and price as a dictionary to price_data
price_data['prices'].append({'social_site': social_site, 'price': value})
logging.info('Price data: %s', price_data['prices'])
if price_data['prices']:
logging.info('Price data is present: %s', price_data)
else:
logging.info('No price data found')
**step2: next step to construct json response**
response_data = {
'message': 'task disapprove successfully',
'success': True,
'prices': price_data,
'influencer': request.GET.get('slug', ''), # Assuming slug is sent via query parameters
'publisher': request.GET.get('user_name', ''), # Assuming user_name is sent via query parameters
}
return JsonResponse(response_data)
**output**
**display json key value pair**
{
"message": "Task disapproved successfully",
"success": true,
"prices": [
{"social_site": "face", "price": "60"},
{"social_site": "youtube", "price": "67"}
{"social_site":"face","price":"34"}
],
"influencer": "rajesh ",
"publisher": "rakeshdev"
}
Top comments (0)