Hello Paty Hernandez,
Greetings! Welcome to Microsoft Q&A Storage.
I understand that you’re trying to append JSON content to an existing JSON object in an Azure Storage Append Blob, but the content is being added as a new JSON array instead of merging with the existing JSON object. To achieve this, you’ll need to read the existing JSON content from the blob, modify it, and then write it back.
Steps to perform the same,
- Read the existing JSON content from the blob.
- Parse the JSON content and modify it.
- Write the updated JSON content back to the blob.
const { BlobServiceClient } = require('@azure/storage-blob');
const appendBlobClient = BlobServiceClient.fromConnectionString('your_connection_string').getContainerClient('your_container_name').getAppendBlobClient('your_blob_name');
async function appendJsonToBlob(newJson) {
try {
// Step 1: Read the existing JSON content from the blob
const downloadBlockBlobResponse = await appendBlobClient.download(0);
const downloadedContent = await streamToString(downloadBlockBlobResponse.readableStreamBody);
let existingJson = JSON.parse(downloadedContent);
// Step 2: Modify the existing JSON content
existingJson = { ...existingJson, ...newJson };
// Step 3: Write the updated JSON content back to the blob
const updatedContent = JSON.stringify(existingJson);
await appendBlobClient.appendBlock(updatedContent, updatedContent.length);
console.log("Upload success");
} catch (error) {
console.error("Error:", error);
}
}
// Helper function to convert stream to string
async function streamToString(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on("data", (data) => {
chunks.push(data.toString());
});
readableStream.on("end", () => {
resolve(chunks.join(""));
});
readableStream.on("error", reject);
});
}
// Example usage
const newJson = { key: "value" };
appendJsonToBlob(newJson);
Note: The above code is an example code, this code reads the existing JSON content from the blob, merges it with the new JSON content, and writes the updated JSON back to the blob. Make sure to replace 'your_connection_string', 'your_container_name', and 'your_blob_name' with your actual Azure Storage details.
Hope the above information helps! please let us know if you have any further queries. I’m happy to assist you further.
Please "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.