Translating JavaSript to Python Script

I have the below script in JavaScript and I want to convert to Python for it to work exactly.

// Get the API data

const apiData = $(‘Fetch Carpark Availability’).first().json.items[0].carpark_data;

// Get the CSV data (assuming the CSV node outputs an array of objects)

const csvData = $input.all();

// Since the CSV node might output multiple items (each row as an item), we need to collect them

let allCsvData = ;

for (let i = 0; i < csvData.length; i++) {

allCsvData.push(csvData[i].json);

}

// Create a mapping from carpark number to availability from API data

const availabilityMap = {};

apiData.forEach(carpark => {

availabilityMap[carpark.carpark_number] = carpark.carpark_info;

});

// Merge the data

const mergedData = allCsvData.map(carpark => {

const carparkNumber = carpark.car_park_no;

return {

...carpark,

availability: availabilityMap\[carparkNumber\] || \[\]

};

});

// Now, we need to return the merged data as multiple items or a single item with an array?

// Since we want to pass multiple carparks, we return each as a separate item.

return mergedData.map(item => ({ json: item }));

Hey @TH1

It starts like this:

apiData = _("Fetch Carpark Availability").first().json["items"][0].carpark_data
csvData = _input.all()

and then it’s pretty much python as you know it. Use print statements to debug and documentation snippets:

and other places in the documentation where you can switch to python to see code examples.

1 Like

Get the API data from the ‘Fetch Carpark Availability’ node

api_data = _(“Fetch Carpark Availability”).first().json[“items”][0].carpark_data

csv_data = _input.all()

Extract JSON from all CSV input items

all_csv_data =
for i in range(len(csv_data)):
all_csv_data.append(csv_data[i].json)

Create mapping from carpark number to availability

availability_map = {}
for carpark in api_data:
availability_map[carpark[‘carpark_number’]] = carpark[‘carpark_info’]

Merge the data

merged_data =
for carpark in all_csv_data:
carpark_number = carpark[‘car_park_no’]

Create a new dictionary with all properties from carpark plus availability

merged_item = {**carpark, ‘availability’: availability_map.get(carpark_number, )}
merged_data.append(merged_item)

Return each item as a separate item with json key

output = [{‘json’: item} for item in merged_data]
return output

actually when you use print() statement, where can we see the output?

When you use print statement, the output is going to go to the developer’s web console

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.