Node.js 双引号 json 数组有什么办法

Is there any way for Node.js Double Quoted json array

提问人:infinityosman 提问时间:11/13/2023 更新时间:11/14/2023 访问量:37

问:

我正在编写一个用于字幕翻译的应用程序。但我有一个问题。我将使用 Microsoft Translater 文本 Api,此 API 需要这种类型的请求正文;

请求正文 请求的正文是一个 JSON 数组。每个数组元素都是一个 JSON 对象,该对象具有一个名为 Text 的字符串属性,该属性表示要翻译的字符串。 存在以下限制:

数组最多可以有 25 个元素。 请求中包含的整个文本不能超过 5,000 个字符(包括空格)。

[
    {
        "Text": "I would really like to drive your car around the block a few times."
    },
    {
        "Text": "Tried something new."
    }
]

我几乎尝试了所有方法。我的期权数据是这样的;

data: [
    { Text: 'Oh! What a nice day!\r' },
    { Text: "Keep going this way! We'll\rsee the navy base soon.\r" },
    { Text: 'Koby! You are good!\r' },
    { Text: 'We got here indeed!\r' },
    { Text: 'Sure...\r' },
    { Text: "That's the basic skill of a sailor!\r" },
    { Text: "You're still in a good mood, Luffy.\r" },
    { Text: 'I heard that he was caught there!\r' },
    { Text: 'The famous bounty hunter Roronoa Zoro!\r' },
    { Text: 'A bloody animal! Hunting down pirates!\r' },
    { Text: '<i>He cuts them into pieces!</i>\r' },
    { Text: `<i>He's a man, known as "the demon".</i>\r` },
    {
      Text: '(Episode 2) "The Great Swordsman!\rBounty Hunter Roronoa Zoro"\r'
    },
    {
      Text: '(Episode 2) "Daikengou Arawaru!\rKaizoku-kari Roronoa Zoro"\r'
    },
    {
      Text: '<i>(Based on Manga ch.3: "Enter Zoro Pirate\rHunter", ch.4: "The Great Captain Morgan"...)</i>\r'
    },
    {
      Text: '<i>(...and ch.5: "The Pirate\rKing And The Master Swordsman")</i>\r'
    },
    { Text: 'We are finally here!\r' },
    { Text: 'Hey Luffy,\r' },
    { Text: "Don't be stupid enough to see him!\r" },
    { Text: "I havn't decided yet\r" },
    { Text: 'depends on whether he\ris a good guy or not.\r' },
    { Text: "He is a bad guy! That's\rwhy he was caught!\r" },
    { Text: 'Uh, is Zoro captured at the base?\r' },
    { Text: "You can't mention that name here!\r" },
    {
      Text: "Let's go there first! Don't\ryou want to join the navy?\r"
    }
  ]

首先,我需要用双引号制作这个 Text 键。其次,我需要用双引号而不是单引号来制作值。这是我的完整代码。

const axios = require('axios');
const fs = require('fs/promises');
const { format } = require('path');
const { v4: uuidv4 } = require('uuid');

async function translateandsave(subtitleBatch) {
  const key = "Text";
  const formattedData = subtitleBatch.map(text => ({ [key]: `"${text}"` }));

  const options = {
    method: 'POST',
    url: 'https://microsoft-translator-text.p.rapidapi.com/translate',
    params: {
      'to[0]': 'tr',
      'api-version': '3.0',
      profanityAction: 'NoAction',
      textType: 'plain'
    },
    headers: {
      'content-type': 'application/json',
      'X-RapidAPI-Key': 'secret!',
      'X-RapidAPI-Host': 'microsoft-translator-text.p.rapidapi.com'
    },
    data: subtitleBatch.map((text) => ({ "Text": text }))

  };
  console.log(options);
  try {
  const response = await axios.request(options);
  const translatedSubtitles = response.data.map(entry => entry.translations[0].text);

  const newSubtitleFilePath = `temp_${uuidv4()}\\translatedSubtitle.srt`;
  await fs.appendFile(newSubtitleFilePath,{ flag: 'wx' }, translatedSubtitles.join('\n'));

  } catch (error) {
  console.error(`Batch translate error:`, error.message);
  }
}


const originalSubtitleFilePath = 'temp_9985f505-1aa0-436b-bb36-025c77759de1\\subtitle_1.srt';
  
async function main() {
  try {
    const originalSubtitleContent = await fs.readFile(originalSubtitleFilePath, 'utf-8');
    const lines = originalSubtitleContent.split('\n');

    const batchSize = 25;
    let subtitleBatch = [];

    let subcounts = [];
    let timecodes = [];
    let texts = [];
    let iscount = true;
    let istimecode = false;
    let istext = false;
    let textcount = 0;
    for (const line of lines) {
      if(line.trim() === '') {
        iscount = true;
        istimecode = false;
        istext = false;
        textcount = 0;
        subtitleBatch.push(texts[texts.length-1]);
        if(subtitleBatch.length === batchSize){
          await translateandsave(subtitleBatch)
          subtitleBatch = [];
        }
        

      }
      else if (iscount===true){
        subcounts.push(line);
        iscount = false;
        istimecode = true;
      }
      else if (istimecode===true){
        timecodes.push(line);
        istimecode = false;
        istext = true;
      }
      else if(istext === true){
        if(textcount === 0){
          texts.push(line);
        }
        else{
          texts[texts.length-1] += line
        }
        textcount++;
      }

    }
  } catch (error) {
    console.error('Error:', error.message);
  }
}

main();

我尝试了text.replace和所有其他东西。

节点 .js 数组 JSON 节点 .js-fs

评论

1赞 tkausl 11/13/2023
仅此而已。JSON.stringify
0赞 apokryfos 11/13/2023
learn.microsoft.com/en-gb/azure/ai-services/translator/......似乎表明钥匙不是(尽管我不确定这是否重要)。除此之外,即使没有 因为 axios 会将 JS 数组转换为 JSON,其中键两边有双引号textText.map
0赞 infinityosman 11/13/2023
当我 JSON.stringize 格式化数据时,选项数据将是 this = data:行的开头和结尾都有一个撇号。所以它成为api的一个问题。@tkausl[{"Text":"\\"depends on whether he\\ris a good guy or not.\\r\\""},{"Text":"\\"He is a bad guy! That's\\rwhy he was caught!\\r\\""} ...........,{"Text":"\\"Uh, is Zoro captured at the base?\\r\\""}]
0赞 infinityosman 11/13/2023
你能给我举个例子,说明如何在没有.map的情况下做到这一点@apokryfos
0赞 derpirscher 11/13/2023
@tkausl自己进行字符串化(并相应地设置正确的字符串化)。如果设置为字符串,则不会设置正确的标头...axiosContent-TypedataContent-Type: application/json

答:

-1赞 infinityosman 11/14/2023 #1

我已经这样解决了我的问题;我想问题出在接受标头中。我已将 添加到我的标题中,它修复了它!任何有问题的人,试试这个。'Accept-Encoding': 'zlib'

async function translatebatch(subtitleBatch) {
  let myObjectArray = [];
  for (let i = 0; i < subtitleBatch.length; i++) {
    let myObject = {};
    myObject["Text"] = subtitleBatch[i];
    myObjectArray.push(myObject); // Oluşturulan nesneyi diziye ekleyin
  }
  const options = {
    method: 'POST',
    url: 'https://microsoft-translator-text.p.rapidapi.com/translate',
    params: {
      'to[0]': 'tr',
      'api-version': '3.0',
      profanityAction: 'NoAction',
      textType: 'plain'
    },
    headers: {
      'Accept-Encoding': 'zlib',
      'content-type': 'application/json',
      'X-RapidAPI-Key': 'secret!',
      'X-RapidAPI-Host': 'microsoft-translator-text.p.rapidapi.com'
    },
    data: JSON.stringify(myObjectArray)

  };
  
  try {
    const response = await axios.request(options);
    response.data.forEach(entry => {
      const translatedText = entry.translations[0].text;
      translatedSubtitle.push(translatedText);
    });
    
  } catch (error) {
    console.error(`Batch translate error:`, error);
  }
}