I am not able to loop through the contents of a JSON file because the JSON file starts with a ‘.’ dot.
How do I clean the JSON file so that it removes the ‘.’ dot in the begining of the file?
Find below my code:
// Fetch API
fetch(apiUrl, {
method: "POST",
headers: headers,
body: JSON.stringify(requestBody),
})
.then(response => response.json())
.then(data => {
// Get the generated response from the API
const generatedResponse = data.choices[0].text;
// Console log out response
console.log("smartResponse:: ", generatedResponse);
for (let section in generatedResponse) {
// Get the prompt for the current section
let prompt = generatedResponse[section].prompt;
// Do something with the prompt, like print it to the console
console.log(`Prompt for ${section}: ${prompt}`);
}
The code above yields:
smartResponse:: .
{
"whatIsABox": {
"prompt": "What is a box?",
"section": "What is a box?"
},
"typesOfBoxes": {
"prompt": "What are the different types of boxes?",
"section": "Types of Boxes"
},
"usesForBoxes": {
"prompt": "What are some uses for boxes?",
"section": "Uses for Boxes"
}
}
Prompt for 0: undefined
Prompt for 1: undefined
Prompt for 2: undefined
Prompt for 3: undefined
Prompt for 4: undefined
The desired result should be:
smartResponse::
{
"whatIsABox": {
"prompt": "What is a box?",
"section": "What is a box?"
},
"typesOfBoxes": {
"prompt": "What are the different types of boxes?",
"section": "Types of Boxes"
},
"usesForBoxes": {
"prompt": "What are some uses for boxes?",
"section": "Uses for Boxes"
}
}
Prompt for What is a box?: A box is a container with six faces. The faces are made of six panels. The panels are attached to each other with hinges or latches. A box has a lid and a bottom.
3
Answers
generatedResponse
is a string, not an object. You need to remove the.
at the beginning, then parse it.Have you tried using for loop like this.
As per the response you mentioned in the OP, Looks like
data.choices[0].text
is returning a string. So to achieve this you can remove/replace that leading dot by usingString.charAt(0)
.Demo :