I
I
Ivan2019-01-19 04:48:28
JavaScript
Ivan, 2019-01-19 04:48:28

How to print JS result on page?

Found a great js that converts XML to JSON on the fly .
The script quickly performs its task, but the result is visible only in the browser.
How to display the result in the page itself in json format so that you can work with it further?
Thank you!

var xml = (function() {
    /*

  <?xml version="1.0" encoding="UTF-8" ?>

  <Results>
  <show>
  <showid>2930</showid>
  <name>Buffy the Vampire Slayer</name>
  <link>http://www.tvrage.com/Buffy_The_Vampire_Slayer</link>
  <country>US</country>
  <started>Mar/10/1997</started>
  <ended>May/20/2003</ended>
  <seasons>7</seasons>
  <status>Ended</status>
  <runtime>60</runtime>
  <classification>Scripted</classification>
  <genres><genre>Action</genre><genre>Adventure</genre><genre>Comedy</genre><genre>Drama</genre><genre>Horror/Supernatural</genre><genre>Mystery</genre><genre>Sci-Fi</genre></genres>
  <network country="US">UPN</network>
  <airtime>20:00</airtime>
  <airday>Tuesday</airday>
  <akas><aka country="SE">Buffy &amp; vampyrerna</aka><aka country="DE">Buffy - Im Bann der Dämonen</aka><aka country="NO">Buffy - Vampyrenes skrekk</aka><aka country="HU">Buffy a vámpírok réme</aka><aka country="FR">Buffy Contre les Vampires</aka><aka country="IT">Buffy l'Ammazza Vampiri</aka><aka country="PL">Buffy postrach wampirów</aka><aka country="BR">Buffy, a Caça-Vampiros</aka><aka country="PT">Buffy, a Caçadora de Vampiros</aka><aka country="ES">Buffy, Cazavampiros</aka><aka country="HR">Buffy, ubojica vampira</aka><aka country="FI">Buffy, vampyyrintappaja</aka><aka country="EE">Vampiiritapja Buffy</aka><aka country="IS">Vampírubaninn Buffy</aka><aka country="RU">Баффи – истребительница вампиров</aka></akas>
  </show>
  <show>
  <showid>31192</showid>
  <name>Buffy the Vampire Slayer - Season Eight: Motion comics</name>
  <link>http://www.tvrage.com/shows/id-31192</link>
  <country>US</country>
  <started>Jul/19/2010</started>
  <ended>Nov/22/2010</ended>
  <seasons>1</seasons>
  <status>Canceled/Ended</status>
  <runtime>15</runtime>
  <classification>Animation</classification>
  <genres><genre>Animation General</genre><genre>Action</genre><genre>Adventure</genre><genre>Comedy</genre><genre>Drama</genre><genre>Horror/Supernatural</genre><genre>Sci-Fi</genre></genres>
  <network country="US">iTunes</network>
  <airtime>12:00</airtime>
  <airday>Tuesday</airday>
  </show>
  <show>
  <showid>2931</showid>
  <name>Buffy the Animated Series</name>
  <link>http://www.tvrage.com/Buffy_the_Animated_Series</link>
  <country>US</country>
  <started>2002</started>
  <ended></ended>
  <seasons>1</seasons>
  <status>Pilot Rejected</status>
  <runtime>4</runtime>
  <classification>Animation</classification>
  <genres><genre>Animation General</genre><genre>Action</genre><genre>Adventure</genre><genre>Horror/Supernatural</genre></genres>
  <network country="US">FOX</network>
  <airtime>12:00</airtime>
  <airday>Tuesday</airday>
  </show>
  </Results>
  */
  }).toString().split('\n').slice(2, -2).join('\n').trim();

  var oParser = new DOMParser();
  var xml = oParser.parseFromString(xml, "text/xml");

  // Changes XML to JSON
  function xmlToJson(xml) {

    // Create the return object
    var obj = {};

    if (xml.nodeType == 1) { // element
    // do attributes
    if (xml.attributes.length > 0) {
      //obj["attributes"] = {};
      for (var j = 0; j < xml.attributes.length; j++) {
      var attribute = xml.attributes.item(j);
      //obj["attributes"][attribute.nodeName] = attribute.nodeValue;
      obj['@' + attribute.nodeName] = attribute.nodeValue;
      }
    }
    } else if (xml.nodeType == 3) { // text
    obj = xml.nodeValue.trim(); // add trim here
    }

    // do children
    if (xml.hasChildNodes()) {
    for (var i = 0; i < xml.childNodes.length; i++) {
      var item = xml.childNodes.item(i);
      var nodeName = item.nodeName;
      // 	console.debug('child',nodeName,item)
      if (typeof(obj[nodeName]) == "undefined") {
      var tmp = xmlToJson(item);
      if (tmp !== "") // if not empty string
        obj[nodeName] = tmp;
      } else {
      if (typeof(obj[nodeName].push) == "undefined") {
        var old = obj[nodeName];
        obj[nodeName] = [];
        obj[nodeName].push(old);
      }
      var tmp = xmlToJson(item);
      if (tmp !== "") // if not empty string
        obj[nodeName].push(tmp);
      }
    }
    }
    if (!Array.isArray(obj) && typeof obj == 'object') {
    var keys = Object.keys(obj);
    if (keys.length == 1 && keys[0] == '#text') return obj['#text'];
    if (keys.length === 0) return null;
    }
    return obj;
  }

  var obj =xmlToJson(xml);
  console.clear();
  console.debug(obj);
  document.getElementById('pre').innerHTML=JSON.stringify(obj,null,'  ');

How do I get data from JSON
public function getMarket($period, $page)
    {
        $items = [];
        $response = (array)@json_decode($this->request('GET', 'https://site.ru/json/my?duration=' . $period . '&page=' . $page)['body'], true);

        foreach ($response as $key => $item) {
            $item['user'] = $this->getUser($item['userId']);
            $items[] = new MyItem($item);
        }

        return $items;
    }

Translating a JavaScript object into a JSON string is done using the JSON.stringify() method.
This method does the opposite of the JSON.parse() method .
Example: var personString = JSON.strigify(person);
Could not implement in practice.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry C, 2019-01-20
@SDmitriyS

Показать xml как есть, можно в <textarea> и <xmp>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question