I have a json of the form:

{"2":{"title":"1","content":"2"}}{"1":{"title":"\u041e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435 \u0441\u0430\u0439\u0442\u0430.","content":"\u041d\u043e\u0432\u044b\u0439 \u0434\u0438\u0437\u0430\u0439\u043d \u0438 \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0430\u044f "}} 

How can I parse it and throw it into a loop in which all the news (this is news in json) is pushed into the block under the id "container" in the form:

 `<div id='title'>Название новости из json</div>` <div id='content'>Содержание новости из json</div> 

This is the news here .

  • one
    You have the original json invalid, first you need to bring it to the standard (for example, you can check on jsonlint.com ). - Vladimir Gamalyan
  • one
    This requires the JSON.parse () function - RussCoder
  • Most likely, you have exactly this situation. ru.stackoverflow.com/questions/305274/… - ilyaplot

1 answer 1

As already noted in the comments, json is not valid. Valid it will be in this form

 {"2":{"title":"1","content":"2"},"1":{"title":"\u041e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435 \u0441\u0430\u0439\u0442\u0430.","content":"\u041d\u043e\u0432\u044b\u0439 \u0434\u0438\u0437\u0430\u0439\u043d \u0438 \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0430\u044f "}} 

In order to display this json in a loop, you need to apply something like this

 .title { font-weight: bold; } 
 <div id="container"></div> <script type="text/javascript"> // Тут получаем json var data = '{"2":{"title":"1","content":"2"},"1":{"title":"\u041e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435 \u0441\u0430\u0439\u0442\u0430.","content":"\u041d\u043e\u0432\u044b\u0439 \u0434\u0438\u0437\u0430\u0439\u043d \u0438 \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0430\u044f "}}'; var dataObject = JSON.parse(data); var container = document.getElementById('container'); for (var k in dataObject) { container.insertAdjacentHTML('beforeend', '<div class="title">'+dataObject[k].title+'</div><div class="content">'+dataObject[k].content+'</div>'); } </script> 

Despite the fact that you are asking to make several elements with the same ID, I gave an example with the class instead of id, because there should not be several identical id in the same html document.

  • How to make it valid? Here is my PHP code: w-0rld.ru/storage/1.txt - W_0rld
  • Output data using json_encode. For the entire data set, this function needs to be used only once. The entire data set must be a single array or object. Your code is not available. 404 - ilyaplot