A
A
Astral1004982020-08-26 10:58:20
JavaScript
Astral100498, 2020-08-26 10:58:20

How to reach nested elements using JSON.parse?

I am developing an extension. After a request to the server, I get a JSON file with nested elements. There is a working piece made using the eval().response method - this is the resulting array

$.ajax({
          method: 'POST',
          url: `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${request.langCode}&dt=t&q=${encodeURI(request.word)}`,
        })
        .done(function (response) {//Обработчик при успешном выполнении 
          
          let range = selectedText.getRangeAt(0);
          let result = '';

          range.deleteContents();// Удаляет выделенную область 
          
          for (let i = 0; i < eval(response)[0].length; i++) {

            result = result + eval(response)[0][i][0];//Достаем из json переведенные слова
          }


How can I parse the last two lines with just JSON.parse?

Received json from the server
[
  [
    [
      "my name is DIMA",
      "мое имя ДИМА",
      null,
      null,
      3,
      null,
      null,
      [
        []
      ],
      [
        [
          [
            "86e6f450b8cc469628ba70bf2947b049",
            "ru_en_2020q2.md"
          ]
        ]
      ]
    ]
  ],
  null,
  "ru",
  null,
  null,
  null,
  1,
  [],
  [
    [
      "ru"
    ],
    null,
    [
      1
    ],
    [
      "ru"
    ]
  ]
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-08-26
@Astral100498

JSON.parse(response);
UPD:

const data = JSON.parse(`{"sentences":[{"trans":"Привет мир","orig":"Hello World","backend":1}],"src":"en","spell":{}}`);

const words = data.sentences.map(sentence => sentence.trans);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question