M
M
Marishka972019-12-09 13:00:58
JavaScript
Marishka97, 2019-12-09 13:00:58

How to extract key from JSON object?

There is a code snippet:

let parsedFile = 0;
  let request = new XMLHttpRequest();
   	request.open('POST','/getJSON', true);
   	request.setRequestHeader("Content-Type", "application/json");
   	request.addEventListener("load", function () {   
   		parsedFile = JSON.parse(request.response);
   		parsedFile = JSON.parse(parsedFile);
   		let newCheck = parsedFile[0];
   		document.getElementById('goodsInTable').innerHTML = parsedFile[0]; //Выдаёт: {"name":"Набор новогодних игрушек","size":"15","price":"980","kind":"шт","type":"Бытовые вещи","value":"40","id":"fcccd5c"}
                document.getElementById('goodsInTable').innerHTML = parsedFile[0].name (или parsedFile[0]['name']) // выдает undefined 
   	});

How to deal with it? I suppose it produces undefined due to the fact that all the keys of the JSON object are in quotes, then another question is how to remove them?
I tried to do parsing, in this form I get a variable that parses the response from the server:
["{"name":"Набор новогодних игрушек","size":"15","pr…type":"Бытовые вещи","value":"40","id":"fcccd5c"}", "{"name":"Порошок TIDE Мятная свежесть","size":"15"…pe":"Бытовая химия","value":"60","id":"f230d384"}", "{"name":"Coca-Cola","size":"2","price":"80","kind"…e":"Вкусовые товары","value":"40","id":"fb892c3"}", "{"name":"Игрушки","size":"2","price":"320",…pe":"Новогодние игрушки","value":"900","id":"f311f50f"}"]

I will be glad if you help with advice on how to make it work. Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Didenko, 2019-12-09
@Dasslier

Use JSON.parse(parsedFile[0]).name

V
Vladimir Korotenko, 2019-12-09
@firedragon

Your json is broken, which the parser honestly reports in the console, compare with the corrected version
https://jsfiddle.net/vkorotenko/47ypd1z3/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question