InvokeURL butchering JSON for OpenAI API calls

InvokeURL butchering JSON for OpenAI API calls

My organization works with mostly educational institutions. We have a custom module called "Schools", which is the user-entered school name they put when using our service (which they enter along with their state and zip code). We want to map this to a list of known schools from a public database that has both a standardized school name, address, phone number, and other data about the school (along with a unique identifier) stored in our org's Zoho Analytics database.

To accomplish this, we are trying to leverage OpenAI's API to find a "best match" of the unique ID. When a school is created in our system, I am getting the "State", "Zip", and entered school name. This runs a query in Zoho Analytics to return batches of 250 schools in that state at a time (to avoid API size problems), and runs this through OpenAI to find which in each batch is the closest match to what was entered, and saves that to a new array. This repeats for all schools in the state, then afterwards runs the set of "winners" through OpenAI one more time to get the best overall winner.

The problem is our API call to OpenAI - it continually returns 

{"error":{"message":"We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not valid JSON. If you have trouble figuring out how to fix this, please contact us through our help center at help.openai.com.)","type":"invalid_request_error","param":null,"code":null}}

I verified several times that my JSON body is indeed correct. I also have alternated between using "parameters" and "body", and various ways to stringify the payload - none of which have any improvement. Recommendations from ChatGPT believe that regardless of me specifying "content-type: application/json", it is still mangling the payload.

The worst part is - this actually worked just fine until last night (October 17, 2025), sometime around 5pm. I had been running the version of the script below to back-fill our existing school database, which had been calling this API every 45 seconds for a couple days without any errors. OpenAI insists they have not changed anything on their end, and zoho insists the same on theirs. Any help would be appreciated.

string standalone.SetSchoolAddressAPI()
{
PAGE_SIZE = 250;
random = randomNumber(1,50);
school = zoho.crm.searchRecords("Schools","(NCES_School_ID:equals:99)",1,random);
st_school_id = school.get(0).get("id");
info st_school_id;
school = zoho.crm.getRecordById("Schools",st_school_id);
school_name = ifnull(school.get("Name"),"");
acc_id = null;
if(school.containsKey("Account") && school.get("Account") != null && school.get("Account").containsKey("id"))
{
acc_id = school.get("Account").get("id");
}
account = Map();
if(acc_id != null)
{
account = zoho.crm.getRecordById("Accounts",acc_id);
}
account = ifnull(account,Map());
school_zip = ifnull(school.get("Zip"),account.get("Billing_Code"));
school_state = ifnull(school.get("State"),account.get("Billing_State"));
target_name = ifnull(school_name,"");
state_input = ifnull(school_state,"");
zip_input = ifnull(school_zip,"");
/***** --- Enforce state presence & normalize --- *****/
if(state_input == null || state_input == "")
{
update_map = Map();
update_map.put("NCES_School_ID",null);
update_map.put("Country","");
update_map.put("State",school_state);
zoho.crm.updateRecord("Schools",st_school_id,update_map);
return "No state on record; aborting NCES match.";
}
state_input = state_input.trim();
/***** === Zoho Analytics fixed config (unchanged) === *****/
workspace_name = "Zoho CRM Analytics";
view_name = "NCES Schools";
owner_email = "xxx";
ws_enc = zoho.encryption.urlEncode(workspace_name);
view_enc = zoho.encryption.urlEncode(view_name);
endpoint = "https://analyticsapi.zoho.com/api/" + owner_email + "/" + ws_enc + "/" + view_enc;
/***** === Step 1: Count rows by state === *****/
state_esc = state_input.replaceAll("'","''");
count_sql = "select count(*) as total_count from \"" + view_name + "\" where \"State\"='" + state_esc + "'";
count_params = Map();
count_params.put("ZOHO_ACTION","EXPORT");
count_params.put("ZOHO_OUTPUT_FORMAT","JSON");
count_params.put("ZOHO_SQLQUERY",count_sql);
count_params.put("ZOHO_API_VERSION","1.0");
count_resp = invokeurl
[
url :endpoint
type :POST
parameters:count_params
connection:"zoho_analytics_conn"
];
total_count = 0;
// First try KV shape: {"data":[{"total_count":"10398"}]}
if(count_resp != null && count_resp.containsKey("data") && count_resp.get("data") != null && count_resp.get("data").size() > 0)
{
tc_raw = count_resp.get("data").get(0).get("total_count");
if(tc_raw != null)
{
total_count = tc_raw.toLong();
}
}
else
{
// Fallback to rows shape:
// {"response":{"result":{"column_order":["total_count"],"rows":[["10398"]]}}}
if(count_resp != null && count_resp.containsKey("response"))
{
resp_obj = count_resp.get("response");
if(resp_obj != null && resp_obj.containsKey("result"))
{
result_obj = resp_obj.get("result");
if(result_obj != null && result_obj.containsKey("rows"))
{
rows_list = result_obj.get("rows");
if(rows_list != null && rows_list.size() > 0)
{
first_row = rows_list.get(0);
// rows are arrays, so first cell holds the count as string
if(first_row != null && first_row.size() > 0)
{
tc_raw2 = first_row.get(0);
if(tc_raw2 != null)
{
total_count = tc_raw2.toLong();
}
}
}
}
}
}
}
/***** === Step 2: Build list of page indexes (Deluge compliant, no while) === *****/
page_map = list();
num_pages = (total_count / PAGE_SIZE).toLong();
if(total_count % PAGE_SIZE > 0)
{
num_pages = num_pages + 1;
}
// use nested for-each loops over a fixed dummy list to reach num_pages
dummy = list();
for each  d in {"a","b","c","d","e","f","g","h","i","j"}
{
// outer loop (10×)
for each  e in {"1","2","3","4","5","6","7","8","9","10"}
{
// inner loop (10×)
if(page_map.size() < num_pages)
{
page_map.add(page_map.size());
}
}
}
/***** === Step 3: For each page, fetch candidates and pick a batch winner via OpenAI === *****/
batch_winners = list();
for each  p in page_map
{
offset_val = p * PAGE_SIZE;
sql_batch = "select \"State\",\"School Name\",\"NCES School ID\",\"Zip\"" + "from \"" + view_name + "\" where \"State\"='" + state_esc + "' " + "limit " + PAGE_SIZE.toString() + " offset " + offset_val.toString();
params = Map();
params.put("ZOHO_ACTION","EXPORT");
params.put("ZOHO_OUTPUT_FORMAT","JSON");
params.put("ZOHO_API_VERSION","1.0");
params.put("KEY_VALUE_FORMAT","true");
params.put("ZOHO_SQLQUERY",sql_batch);
count_params.put("ZOHO_API_VERSION","1.0");
resp_batch = invokeurl
[
url :endpoint
type :POST
parameters:params
connection:"zoho_analytics_conn"
];
/***** Parse candidates safely no matter the response shape *****/
candidates = list();
if(resp_batch != null)
{
// Case 1: Key-value format (normal Zoho Analytics JSON)
if(resp_batch.containsKey("data") && resp_batch.get("data") != null)
{
candidates = resp_batch.get("data");
}
// Case 2: Nested "response" > "result" > "rows" format
else if(resp_batch.containsKey("response"))
{
resp_obj = resp_batch.get("response");
if(resp_obj != null && resp_obj.containsKey("result"))
{
result_obj = resp_obj.get("result");
if(result_obj != null && result_obj.containsKey("rows"))
{
rows_list = result_obj.get("rows");
// convert matrix rows into list of maps for consistency
for each  row_item in rows_list
{
row_map = Map();
// optional: if you have column_order, map by index
if(result_obj.containsKey("column_order"))
{
cols = result_obj.get("column_order");
idx = 0;
for each  col in cols
{
if(row_item.size() > idx)
{
row_map.put(col,row_item.get(idx));
}
idx = idx + 1;
}
}
candidates.add(row_map);
}
}
}
}
}
if(candidates.isEmpty())
{
info "No candidates found for this page (state=" + state_input + ")";
continue;
}
/***** Build compact OpenAI prompt for this batch *****/
cand_lines = "";
for each  c in candidates
{
id_short = ifnull(c.get("NCES School ID"),"");
name_short = ifnull(c.get("School Name"),"");
if(name_short != null && name_short.length() > 60)
{
name_short = name_short.substring(0,60);
}
zip_short = ifnull(c.get("Zip"),"");
if(zip_short != null && zip_short.length() > 10)
{
zip_short = zip_short.substring(0,10);
}
delimiter = "###";
// define this once before the loop if not already defined
record_sep = " || ";
// separates candidate rows, readable and single-line
cand_lines = cand_lines + id_short + "|" + name_short + "|" + zip_short + record_sep;
}
// === Build simplified OpenAI request (no line breaks) ===
prompt = "TARGET=" + target_name + "|" + zip_input + delimiter + "CANDIDATES=" + cand_lines + delimiter + "Return ONLY JSON {\"nces_school_id\": string|null, \"confidence\": number}";
messages = List();
messages.add({"role":"system","content":"Match the user-entered school to the best NCES candidate using NAME similarity and ZIP proximity. The delimiter is " + delimiter + "."});
messages.add({"role":"user","content":prompt});
req_body = Map();
req_body.put("model","gpt-4o-mini");
req_body.put("temperature",0);
req_body.put("messages",messages);
ai_resp = invokeurl
[
url :"https://api.openai.com/v1/chat/completions"
type :POST
parameters:req_body.toString()
connection:"openai_custom"
];
// ========== Step 4: Inspect result ==========
best_id = "";
best_conf = 0.0;
raw_content = ai_resp.get("choices").get(0).get("message").get("content");
// Remove markdown fences if present
cleaned = raw_content.replaceAll("(?s)```json|```","").trim();
parsed = cleaned.toMap();
school_id = parsed.get("nces_school_id");
confidence = parsed.get("confidence");
for each  c in candidates
{
if(c.get("NCES School ID") == school_id)
{
if(confidence > 0.8)
{
//do not put low-confidence candidates in the winner batch
c.put("confidence",confidence);
batch_winners.add(c);
break;
}
}
}
}
/***** === Step 4: Final round — pick overall best among batch winners === *****/
if(batch_winners.size() == 0)
{
update_map = Map();
update_map.put("NCES_School_ID",null);
update_map.put("Country","");
update_map.put("State",school_state);
zoho.crm.updateRecord("Schools",st_school_id,update_map);
info "No candidates found for state=" + state_input;
}
winner_lines = "";
for each  w in batch_winners
{
id_short = ifnull(w.get("NCES School ID"),"");
name_short = ifnull(w.get("School Name"),"");
if(name_short != null && name_short.length() > 60)
{
name_short = name_short.substring(0,60);
}
zip_short = ifnull(w.get("Zip"),"");
if(zip_short != null && zip_short.length() > 10)
{
zip_short = zip_short.substring(0,10);
}
delimiter = "###";
// define this once before the loop if not already defined
record_sep = " || ";
// separates candidate rows, readable and single-line
winner_lines = winner_lines + id_short + "|" + name_short + "|" + zip_short + record_sep;
}
// === Build simplified OpenAI request (no line breaks) ===
prompt = "TARGET=" + target_name + "|" + zip_input + delimiter + "CANDIDATES=" + winner_lines + delimiter + "Return ONLY JSON {\"nces_school_id\": string|null, \"confidence\": number}";
messages = List();
messages.add({"role":"system","content":"Match the user-entered school to the best NCES candidate using NAME similarity and ZIP proximity. The delimiter is " + delimiter + "."});
messages.add({"role":"user","content":prompt});
req_body = Map();
req_body.put("model","gpt-4o-mini");
req_body.put("temperature",0);
req_body.put("messages",messages);
final_ai = invokeurl
[
url :"https://api.openai.com/v1/chat/completions"
type :POST
parameters:req_body.toString()
connection:"openai_custom"
];
selected_nces = "";
confidence = 0.0;
contentText = final_ai.get("choices").get(0).get("message").get("content");
// Step 2: Sanitize it — remove code block markers and trim spaces/newlines
cleanText = contentText.replaceAll("```json","");
cleanText = cleanText.replaceAll("```","");
cleanText = cleanText.trim();
// Step 3: Parse the cleaned string as JSON
contentJSON = cleanText.toMap();
// Step 4: Extract the NCES/NCAS ID
selected_nces = contentJSON.get("nces_school_id");
/***** === Step 5: Find selected record and update CRM (unchanged) === *****/
/***** === Step 2: Fetch single row by NCES School ID === *****/
row_sql = "select \"NCES School ID\", \"Website\", \"Address\", \"Address 2\", \"City\", \"State\", \"Zip\", \"Phone\", \"Grade Level\" " + "from \"" + view_name + "\" " + "where \"NCES School ID\" = '" + selected_nces + "' " + "limit 1";
row_params = Map();
row_params.put("ZOHO_ACTION","EXPORT");
row_params.put("ZOHO_OUTPUT_FORMAT","JSON");
row_params.put("ZOHO_SQLQUERY",row_sql);
row_params.put("ZOHO_API_VERSION","1.0");
row_resp = invokeurl
[
url :endpoint
type :POST
parameters:row_params
connection:"zoho_analytics_conn"
];
/***** === Step 3: Parse response and assign variables === *****/
nces_id_final = "";
Website_final = "";
Address_final = "";
Address2_final = "";
City_final = "";
State_final = "";
Zip_final = "";
Phone_final = "";
Grade_final = "";
// First check for JSON KV structure
if(row_resp != null && row_resp.containsKey("data") && row_resp.get("data") != null && row_resp.get("data").size() > 0)
{
row_data = row_resp.get("data").get(0);
nces_id_final = selected_nces;
Website_final = ifnull(row_data.get("Website"),"");
Address_final = ifnull(row_data.get("Address"),"");
Address2_final = ifnull(row_data.get("Address 2"),"");
City_final = ifnull(row_data.get("City"),"");
State_final = ifnull(row_data.get("State"),"");
Zip_final = ifnull(row_data.get("Zip"),"");
Phone_final = ifnull(row_data.get("Phone"),"");
Grade_final = ifnull(row_data.get("Grade Level"),"");
}
else
{
// Fallback for "rows" format
if(row_resp != null && row_resp.containsKey("response"))
{
resp_obj = row_resp.get("response");
if(resp_obj != null && resp_obj.containsKey("result"))
{
result_obj = resp_obj.get("result");
if(result_obj != null && result_obj.containsKey("rows"))
{
rows_list = result_obj.get("rows");
if(rows_list != null && rows_list.size() > 0)
{
first_row = rows_list.get(0);
if(first_row != null && first_row.size() >= 9)
{
nces_id_final = ifnull(first_row.get(0),"");
Website_final = ifnull(first_row.get(1),"");
Address_final = ifnull(first_row.get(2),"");
Address2_final = ifnull(first_row.get(3),"");
City_final = ifnull(first_row.get(4),"");
State_final = ifnull(first_row.get(5),"");
Zip_final = ifnull(first_row.get(6),"");
Phone_final = ifnull(first_row.get(7),"");
Grade_final = ifnull(first_row.get(8),"");
}
}
}
}
}
}
country = "USA";
if(isNull(State_final))
{
country = "";
}
update_map = Map();
update_map.put("NCES_School_ID",nces_id_final);
update_map.put("School_Website",Website_final);
update_map.put("Address",Address_final);
update_map.put("Address_2",Address2_final);
update_map.put("City",City_final);
update_map.put("State",State_final);
update_map.put("Zip",Zip_final);
update_map.put("School_Phone",Phone_final);
update_map.put("Grade_Level",Grade_final);
update_map.put("Country",country);
update_rec = zoho.crm.updateRecord("Schools",st_school_id,update_map);
info st_school_id + " Updated";
/***** === Diagnostics === *****/
diag = Map();
diag.put("school_id",st_school_id);
diag.put("selected_nces_school_id",nces_id_final);
diag.put("model_confidence",confidence);
used_fallback = false;
if(selected_nces == "" || selected_nces == null)
{
used_fallback = true;
}
diag.put("used_fallback",used_fallback);
return diag.toString();
}
    • Recent Topics

    • New Series Announcement - Ecommerce Marketing Tips

      Running an online business is more than just having a website. It’s about getting the right customers to discover you, trust you, and keep coming back. To support your growth journey, we’re launching a weekly Marketing Tips series right here on Zoho Commerce
    • Client Script | Update - Introducing Subform Events and Actions

      Are you making the most of your subforms in Zoho CRM? Do you wish you could automate subform interactions and enhance user experience effortlessly? What if you had Client APIs and events specifically designed for subforms? We are thrilled to introduce
    • {"errors":[{"id":"500","title":"Servlet execution threw an exception"}]}

      Here's the call to move a file to trash. The resource_id is accurate and the file is present. header = Map(); header.put("Accept","application/vnd.api+json"); data = Map(); data_param1 = Map(); att_param1 = Map(); att_param1.put("status",51); data_param1.put("attributes",att_param1);
    • Converting Sales Order to Invoice via API; Problem with decimal places tax

      We are having problems converting a Sales Order to an Invoice via API Call. The cause of the issue is, that the Tax value in a Sales Order is sometimes calculated with up to 16 decimal places (e.g. 0.8730000000000001). The max decimal places allowed in
    • Zoho Canvas - Custom templates for related lists

      Hi, I see that the example pages load always one of our related lists in a custom template, but I dont know how to work with that:  1) How can i make my own custom templates for related lists?  2) Where and how can i check out existing custom templates?
    • Kaizen #147 - Frequently Asked Questions on Zoho CRM Widgets

      Heya! It's Kaizen time again, folks! This week, we aim to address common queries about Zoho CRM Widgets through frequently asked questions from our developer forum. Take a quick glance at these FAQs and learn from your peers' inquiries. 1. Where can I
    • Notebook font size issue

      If I copy something from somewhere and paste it in my notebook, the font size becomes smaller.
    • open word file in zoho writer desktop version

      "How can I open a Microsoft Word (.doc or .docx) file in Zoho Writer if I only have the file saved on my computer and Zoho Writer doesn't appear as an option when I try 'Open with'? Is there a way to directly open the .doc file in Zoho Writer?"
    • Zoho PDF editor has a lot of issues.

      Zoho PDF editor needs a lot of work. It hangs and glitches a lot. Deletes annotations and clearings randomly.
    • Zohom mail

      Plz resolve the problem . I hope u understand .
    • stock

      bom/bse : stock details or price =STOCK(C14;"price") not showing issue is #N/A! kindly resolve this problem
    • Zoho sheet desktop version

      Hi Zoho team Where can I access desktop version of zoho sheets? It is important as web version is slow and requires one to be online all the time to do even basic work. If it is available, please guide me to the same.
    • ZOHO SHEETS

      Where can I access desktop version of zoho sheets? It is important to do basic work If it is available, please guide me to the same
    • Zoho Books - France

      L’équipe de Zoho France reçoit régulièrement des questions sur la conformité de ses applications de finances (Zoho Books/ Zoho Invoice) pour le marché français. Voici quelques points pour clarifier la question : Zoho Books est un logiciel de comptabilité
    • Using Zoho Flow to create sales orders from won deal in Zoho CRM

      Hi there, We are using Zoho Flow to create sales orders automatically when a deal is won in Zoho CRM. However, the sales order requires "Product Details" to be passed in "jsonobject", and is resulting in this error: Zoho CRM says "Invalid input for invalid
    • Is Zoho Sheet available for Linux ?

      Is Zoho Sheet available for Linux ?
    • Bharat

      a
    • how to disable staff selection Zoho Booking integrated to SalesIQ?

      currently there is only one Consultant in my Zoho Bookings like this I integrate Zoho Bookings into Zoho SalesIQ to create a chatbot. Unfortunately, even though I only have one consultant for a consultation, the user have to pick the consultant. It will
    • Zoho Bookings No Sync with Outlook

      Zoho Bookings appointments are showing on my Outlook Calendar but Outlook events are not showing on Zoho Bookings. How do I fix this?
    • End Date in Zoho Bookings

      When I give my appointments a 30 minutes time I would expect the software not to even show the End Time.  But it actually makes the user pick an End Time.  Did I just miss a setting?  
    • Custom confirmation message

      How can I change the message that users see after they submit the booking form? I have to confirm some details before their appointment is officially "confirmed", so I want to change it where it doesn't say their appointment is "confirmed" but rather
    • Issue showing too many consultations in my workspace link.

      Hi Team, I’ve set up two Workspaces to track meetings from different sources. So far, this has been working well, and the two Workspaces are differentiated without any issues. However, when I navigate to Consultations and share the link to my personal
    • Deluge sendmail in Zoho Desk schedule can't send email from a verified email address

      I am trying to add a scheduled action with ZDesk using a Deluge function that sends a weekly email to specific ticket client contacts I've already verified the email address for use in ZDesk, but sendmail won't allow it in its "from:" clause. I've attached
    • Zoho Learn & Zoho Connect

      Hi, Is there a way to sync the knowledge base we have in Zoho Learn with the manuals section is Zoho Connect? Thanks,
    • Addin Support in Zoho Sheet

      Is there any addin support available in zoho sheet as like google marketplace to enhance productivity by connecting with other apps, providing AI data analysis, streamlining business processes, and more?
    • Changing Corporate Structure - How Best to Adapt Current and Future Zoho Instances

      My current company is Company A LLC with a dba ("doing business as" - essentially an alias) Product Name B. Basically, Company A is the legal entity and Product Name B is what customers see, but it's all one business right now. We currently have a Zoho
    • how to add subform over sigma in the CRM

      my new module don't have any subform available any way to add this from sigma or from the crm
    • How to Install Zoho Workdrive Desktop Sync for Ubuntu?

      Hi. I am newbie to Linux / Ubuntu. I downloaded a tar.gz file from Workdrive for installing the Workdrive Desktop Sync tool. Can someone give me step by step guide on how to install this on Ubuntu? I am using Ubuntu 19.04. Regards Senthil
    • How to upload own video?

      How can you upload your own video on your zoho website? I do not want to use another host, but i want to insert my own files. how can i do this?
    • Support new line in CRM Multiline text field display in Zoho Deluge

      Hi brainstrust, We have a Zoho CRM field which is a Muti Line (Small) field. It has data in it that has a carriage return after each line: When I pull that data in via Deluge, it displays as: I'm hoping a way I can change it from: Freehand : ENABLED Chenille
    • Announcing new features in Trident for Windows (v.1.32.5.0)

      Hello Community! Trident for Windows just got better! This update includes new features designed to improve and simplify email and calendar management—and it includes a feature you’ve been waiting for. Let’s dive into what’s new! Save emails in EML or
    • How to render either thumbnail_url or preview_url or preview_data_url

      I get 401 Unauthorised when using these urls in the <img> tag src attribute. Guide me on how to use them!
    • Zoho CRM Calendar | Custom Buttons

      I'm working with my sales team to make our scheduling process easier for our team. We primary rely on Zoho CRM calendar to organize our events for our sales team. I was wondering if there is a way to add custom button in the Calendar view on events/meeting
    • Create Lead Button in Zoho CRM Dashboard

      Right now to create Leads in the CRM our team is going into the Lead module, selecting the "Create Lead" button, then building out the lead. Is there anyway to add the "Create Lead" button or some sort of short cut to the Zoho CRM Dashboard to cut out
    • Searching customer field

      Hello, When entering a receipt, we select customer information. The customer information is synced with Zoho CRM. However, we can't find the customer information because it searches for words that begin with the entered value. It needs to search for words
    • Introducing Version-3 APIs - Explore New APIs & Enhancements

      Happy to announce the release of Version 3 (V3) APIs with an easy to use interface, new APIs, and more examples to help you understand and access the APIs better. V3 APIs can be accessed through our new link, where you can explore our complete documentation,
    • Zoho CRM Tracking Google Enhanced Conversions

      Can anyone @Zoho, consultants, or users help me understand if Zoho CRM is going to support Google's Enhanced Conversions? I included some information from Google below about it. We use Google Adwords for our pay per click advertising for lead generation,
    • zoho click, and nord VPN

      Unfortunately, we've been having problems with Zoho Click, where essentially the line cuts off after about a minute's worth of conversation every time we are on VPN. Is there a way we can change this within the settings so it does not cut the line off
    • Connecting Portals from different Zoho apps

      Hi, I note that Zoho has functionality for customer portals for several of the Zoho apps, like CRM, Projects, Desk etc. Is there any way to connect these portals?  It would be great if we could give our customers access to a portal in which they could
    • Billing Management: #5 Usage Billing

      After understanding the nuances of Advance Billing and Retainers, we will explore one of the booming billing models. Long ago, villagers drew water from a shared well in a small village. The well was a lifeline for the entire community. Ravi, the well
    • Next Page