How to extract values from a JSON response after converting associative array
How to extract values from a JSON response after converting associative array
{
"data": {
"regNo": "DL9CAM9757",
"vehicleManufacturerName": "HYUNDAI MOTOR INDIA LTD",
"model": "I20 ASTA VTVT",
"regDate": "22-May-2017",
"vehicleInsuranceCompanyName": "Acko General Insurance Limited",
"vehicleInsuranceUpto": "22-Apr-2025",
"vehicleInsurancePolicyNumber": "DCCR10178118852/00",
"dbResult": false,
"commercial": false
}
}
$response = Http::withHeaders([
'Authorization' => 'Bearer bb1e37ad58ff4e8dab4e5341bdad3d==', // API token
'apiKey' => '$motoshare_insurance@2025', // Custom API key
'clientId' => 'motoshare_insurance', // Client identifier
])->get("https://api.cuvora.com/car/partner/v3/search", [
'vehicle_num' => $vehicleno, // Vehicle number being searched
]);
// Convert the response to an associative array
$data = $response->json();
// Extract the vehicle manufacturer name safely using null coalescing operator
$vehicleManufacturer = $data['data']['vehicleManufacturerName'] ?? null;
// Use the value
if ($vehicleManufacturer) {
echo "Vehicle Manufacturer: " . $vehicleManufacturer;
} else {
echo "Manufacturer data not found.";
}
How to extract values from a nested JSON response after converting associative array
{
"status": 200,
"message": "Challan Details Found",
"results": [
{
"offences": [
{
"offenceId": 0,
"offenceName": "Driving Two-wheeled without helmets ( Section 194 D of MVA 1988 RW section 129 of CMVA and rule 121 of U.P. MVR 1998. ) ",
"mva": "",
"mva1": "",
"penalty": 0
}
],
"customOffence": [],
"ownerName": "DHARAMVEER SINGH",
"amount": 1000,
"challanNo": "UP89376231027145546",
"status": "Paid",
"dateTime": "2023-10-27",
"docNo": "DL5SCR1965",
"stateCd": "UP",
"dptCd": 0,
"rtoCd": 0,
"paymentDate": "2023-11-30",
"paymentSource": "ONLINE",
"courtStatus": 0,
"courtName": "",
"courtAddress": "",
"trafficPolice": 0,
"sentToCourtOn": "",
"pdfUrl": "",
"receiptUrl": "",
"validContactNo": 0,
"officeName": "",
"officeText": "",
"paymentEligible": 0,
"statusTxt": "",
"source": ""
}
],
"totalChallan": 1
}
$response = Http::withHeaders([
'Authorization' => 'Bearer bb1e37ad58ff4e8dab4e5341bdad3d==',
'apiKey' => '$motoshare_insurance@2025',
'clientId' => 'motoshare_insurance',
])->get("https://api.cuvora.com/car/partner/v3/search", [
'vehicle_num' => $vehicleno,
]);
$vehicleData= $response->json();
'vehicle_manufacturer' => $vehicleData['data']['vehicleManufacturerName'] ?? null,
$challanresponse = Http::withHeaders([
'Authorization' => 'Bearer a1f6d3e584514a129763b0aa47c8dd==',
'apiKey' => '$moto_share_challan_pro@2025',
'clientId' => 'moto_share_challan_pro',
])->get("https://api.cuvora.com/car/partner/v3/challan-pro", [
'vehicle_num' => $vehicleno,
]);
$challanData =$challanresponse->json()
1.$total_challan = $challanData['totalChallan'];
2.$result = $challanData['results'][0];
$offenceName = $result['offences'][0]['offenceName'] ?? null;
How to extract and filter vehicle data from the JSON array of objects
data = {
"data": [
{
"regNo": "DL9CAM9757",
"vehicleManufacturerName": "HYUNDAI MOTOR INDIA LTD",
"model": "I20 ASTA VTVT",
"regDate": "22-May-2017",
"vehicleInsuranceCompanyName": "Acko General Insurance Limited",
"vehicleInsuranceUpto": "22-Apr-2025",
"vehicleInsurancePolicyNumber": "DCCR10178118852/00",
"dbResult": False,
"commercial": False
},
{
"regNo": "DL8CAM1234",
"vehicleManufacturerName": "TOYOTA INDIA",
"model": "INNOVA CRYSTA",
"regDate": "10-Jan-2024",
"vehicleInsuranceCompanyName": "Bajaj Allianz",
"vehicleInsuranceUpto": "10-Jan-2025",
"vehicleInsurancePolicyNumber": "Bajaj234234",
"dbResult": True,
"commercial": True
}
# Add more vehicle data as needed
]
}
$data = $response->json();
// Initialize an array to store filtered results
$filteredData = [];
// Loop through each item in the data and check if the regDate is in 2024
foreach ($data['data'] as $vehicleData) {
// Check if the regDate is in 2024
$regDate = strtotime($vehicleData['regDate']);
if ($regDate !== false && date('Y', $regDate) == '2024') {
// Add the vehicle data to the filtered results array
$filteredData[] = [
'reg_no' => $vehicleData['regNo'] ?? null,
];
}
}
How to extract and filter vehicle data from the JSON array of objects
vehicleno = request.args.get('vehicle_num')
# Make sure the vehicle number is provided
if not vehicleno:
return jsonify({"error": "vehicle_num is required"}), 400
# Set the headers and API parameters
headers = {
'Authorization': 'Bearer a1f6d3e584514a129763b0aa47c8dd==',
'apiKey': '$moto_share_challan_pro@2025',
'clientId': 'moto_share_challan_pro'
}
# Define the API URL
url = "https://api.cuvora.com/car/partner/v3/challan-pro"
# Make the GET request to the external API
response = requests.get(url, headers=headers, params={'vehicle_num': vehicleno})
json_response=jsonify(response.json())
filtered_data = []
for vehicle in data['data']:
reg_date = datetime.strptime(vehicle['regDate'], "%d-%b-%Y") # Convert to datetime object
if reg_date.year == 2024: # Check if year is 2024
filtered_data.append({
})
return jsonify(filtered_data)
how to store data in json string in Database after building associative array from third party api json response
$challanData = [
'owner_name' => $result['ownerName'] ?? null,
'amount' => $result['amount'] ?? 0,
'challan_no' => $result['challanNo'] ?? null,
'status' => $result['status'] ?? null,
]
$response = json_encode($challanData); // Storing the array as a JSON string
DB::table('challan_details')->insert([
'vender_id' => $vender,
'response' => json_encode($jsonData), // Storing the JSON data in 'response' field
]);
how to store data in json string in Database after building associative array from third party api json response in python flask
result = response.json()
# Create the associative array (dictionary)
challan_data = {
'owner_name': result.get('ownerName', None),
'amount': result.get('amount', 0),
'challan_no': result.get('challanNo', None),
'status': result.get('status', None)
}
# Convert the dictionary to a JSON string
json_response = json.dumps(challan_data) // Convert the dictionary to a JSON string
new_challan = ChallanDetails(vender_id=vender_id, response=json_response)
how to convert array to json response and store in database
$vehicleDetails = [
'regNo' => 'DL9CAM9757',
'vehicleManufacturerName' => 'HYUNDAI MOTOR INDIA LTD',
'dbResult' => false,
'commercial' => false
];
$vehicle = Challan::create($vehicleDetails);
// Return response as JSON
return response()->json([
'data' => $vehicleDetails
]);
http://your-app-url/api/vehicle-details
{
"data": {
"regNo": "DL9CAM9757",
"vehicleManufacturerName": "HYUNDAI MOTOR INDIA LTD",
}
}
=========how to convert array to json in PYTHON FLASK===========
vehicle_details = {
'regNo': 'DL9CAM9757',
'vehicleManufacturerName': 'HYUNDAI MOTOR INDIA LTD',
'dbResult': False,
'commercial': False
}
# Return the vehicle details as a JSON response
return jsonify({'data': vehicle_details})
========how to convert array to nested json response==============
public function getChallanDetails()
{
// Simulated data (replace with actual data retrieval from database or other sources)
$challanDetails = [
'offences' => [
[
'offenceId' => 0,
'offenceName' => "Driving Two-wheeled without helmets ( Section 194 D of MVA 1988 RW section 129 of CMVA and rule 121 of U.P. MVR 1998. )",
'mva' => "",
'mva1' => "",
'penalty' => 0
]
],
'customOffence' => [],
'ownerName' => 'DHARAMVEER SINGH',
'amount' => 1000,
'paymentEligible' => 0,
'statusTxt' => '',
'source' => ''
];
// Return response as nested JSON
return response()->json([
'status' => 200,
'message' => 'Challan Details Found',
'results' => [$challanDetails],
'totalChallan' => 1
]);
}
ChallanData::create([
'challan_json' => $challanData // Store the data as an array
]);
How to create dynamic json response from database
challan_data = Challan.query.filter_by(owner_name="DHARAMVEER SINGH").all()
if not challan_data:
return jsonify({
"status": 400,
"message": "No Challan Found",
"results": [],
"totalChallan": 0
})
results = []
# Loop through each challan and fetch its offences
for challan in challan_data:
offences = []
for offence in challan.offences:
offences.append({
"offenceId": offence.id,
"offenceName": offence.offence_name,
})
# Add each challan data with its offences
results.append({
"offences": offences,
"customOffence": [],
"ownerName": challan.owner_name,
"amount": challan.amount,
"challanNo": challan.challan_no,
"source": ""
})
# Response structure
response = {
"status": 200,
"message": "Challan Details Found",
"results": results,
"totalChallan": len(results)
}
How to create dynamic nested json response from database in laravel
$challans = Challan::where('owner_name', 'DHARAMVEER SINGH')->with('offences')->get();
// Check if we have any challans for the person
if ($challans->isEmpty()) {
return response()->json([
'status' => 400,
'message' => 'No Challan Found',
'results' => [],
'totalChallan' => 0
]);
}
// Initialize the response structure
$results = [];
// Loop through each challan and structure the data
foreach ($challans as $challan) {
$offences = [];
// Loop through the offences for each challan
foreach ($challan->offences as $offence) {
$offences[] = [
'offenceId' => $offence->id,
'offenceName' => $offence->offence_name,
'mva' => $offence->mva,
'mva1' => $offence->mva1,
'penalty' => $offence->penalty
];
}
// Add the challan details and offences to the results
$results[] = [
'offences' => $offences,
'customOffence' => [],
'ownerName' => $challan->owner_name,
'amount' => $challan->amount,
'challanNo' => $challan->challan_no,
'status' => $challan->status,
'dateTime' => $challan->date_time,
'docNo' => $challan->doc_no,
'stateCd' => $challan->state_cd,
'dptCd' => 0,
'rtoCd' => 0,
'paymentDate' => $challan->payment_date,
'paymentSource' => $challan->payment_source,
'courtStatus' => 0,
'courtName' => '',
'courtAddress' => '',
'trafficPolice' => 0,
'sentToCourtOn' => '',
'pdfUrl' => '',
'receiptUrl' => '',
'validContactNo' => 0,
'officeName' => '',
'officeText' => '',
'paymentEligible' => 0,
'statusTxt' => '',
'source' => ''
];
}
// Return the structured data as JSON
return response()->json([
'status' => 200,
'message' => 'Challan Details Found',
'results' => $results,
'totalChallan' => count($results)
]);
How to create complex dynamic nested json response from database in laravel
public function storeErrorLogs(Request $request)
{
// Example of fetching data from the database (this would be your query result)
$results = DB::select("YOUR SQL QUERY HERE");
// Initialize an array to store the parent-child-grandchild structure
$parent_child_grandchild = [];
// Loop through the query results to structure them as parent-child-grandchild
foreach ($results as $row) {
$parent_id = $row->parent_id;
$parent_name = $row->parent_name;
$logs = $row->logs; // LogSplitting.logs
$splitting_log = $row->splitting_log; // LogSplitting.Splitting_log
// Initialize parent if not already present
if (!isset($parent_child_grandchild[$parent_id])) {
$parent_child_grandchild[$parent_id] = [
"error_category_id" => $parent_id,
"errorcategory" => $parent_name,
"children" => []
];
}
// Initialize child (error_value) if not already present under parent
if (!isset($parent_child_grandchild[$parent_id]["children"][$error_value])) {
$parent_child_grandchild[$parent_id]["children"][$error_value] = [
"error_value" => $error_value,
"logs" => []
];
}
// Add the log (grandchild) data under the corresponding error_value
$parent_child_grandchild[$parent_id]["children"][$error_value]["logs"][] = [
"prompt_msg" => $prompt_msg,
"logs" => $logs,
"splitting_log" => $splitting_log
];
}
// Store the result in the database
ErrorLog::create([
'parent_child_grandchild' => json_encode($parent_child_grandchild) // Store as JSON
]);
return response()->json([
'status' => 200,
'message' => 'Error Logs Stored Successfully',
'data' => $parent_child_grandchild
]);
}
}
output
{
"1": {
"error_category_id": 1,
"errorcategory": "Engine Issues",
"children": {
"Error Code 101": {
"error_value": "Error Code 101",
"logs": [
{
"prompt_msg": "Engine malfunction detected",
"logs": "Log Entry 1",
"splitting_log": "Splitting Log 1"
},
{
"prompt_msg": "Engine overheating",
"logs": "Log Entry 2",
"splitting_log": "Splitting Log 2"
}
]
},
"Error Code 102": {
"error_value": "Error Code 102",
"logs": [
{
"prompt_msg": "Oil pressure low",
"logs": "Log Entry 3",
"splitting_log": "Splitting Log 3"
}
]
}
}
},
"2": {
"error_category_id": 2,
"errorcategory": "Transmission Issues",
"children": {
"Error Code 201": {
"error_value": "Error Code 201",
"logs": [
{
"prompt_msg": "Transmission fluid low",
"logs": "Log Entry 4",
"splitting_log": "Splitting Log 4"
}
]
}
}
}
}
How to convert json data to php array or object
$dataArray = json_decode($jsonData, true);
How to decodes the incoming JSON request body in Python dictionary
data = request.get_json()
Top comments (0)