<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Серый форум &mdash; JS: забавный способ работы с JSON]]></title>
		<link>http://forum.script-coding.com/viewtopic.php?id=16118</link>
		<atom:link href="http://forum.script-coding.com/extern.php?action=feed&amp;tid=16118&amp;type=rss" rel="self" type="application/rss+xml" />
		<description><![CDATA[Недавние сообщения в теме «JS: забавный способ работы с JSON».]]></description>
		<lastBuildDate>Thu, 25 Feb 2021 15:17:57 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[Re: JS: забавный способ работы с JSON]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=146494#p146494</link>
			<description><![CDATA[<div class="quotebox"><cite>Rumata пишет:</cite><blockquote><p>ведь есть json2.js, достаточно надежный и, по возможности, максимально приближенный к нативной реализации</p></blockquote></div><p>Полностью согласен.</p>]]></description>
			<author><![CDATA[null@example.com (Xameleon)]]></author>
			<pubDate>Thu, 25 Feb 2021 15:17:57 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=146494#p146494</guid>
		</item>
		<item>
			<title><![CDATA[Re: JS: забавный способ работы с JSON]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=146488#p146488</link>
			<description><![CDATA[<p>Я попробовал оба Ваших примера с JSON. Получается интересное решение. Надо будет как-нибудь помедитировать над ними.<br />Но особо не надо -- ведь есть json2.js, достаточно надежный и, по возможности, максимально приближенный к нативной реализации.</p>]]></description>
			<author><![CDATA[null@example.com (Rumata)]]></author>
			<pubDate>Thu, 25 Feb 2021 06:57:42 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=146488#p146488</guid>
		</item>
		<item>
			<title><![CDATA[Re: JS: забавный способ работы с JSON]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=146487#p146487</link>
			<description><![CDATA[<p><strong>Rumata</strong>, такой вариант подошёл ? Есть предложения как упростить улучшить ? <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /></p><p><strong>UPD:</strong> Подумал ещё. Можно проще:<br /></p><div class="codebox"><pre><code>
var JSON = (function(){
	var document = new ActiveXObject(&#039;htmlfile&#039;);
	document.write(&#039;&lt;meta http-equiv=&quot;x-ua-compatible&quot; content=&quot;IE=Edge&quot;&gt;&#039;);
	var JScript = document.Script, JSON = JScript.JSON;
	if(!JSON) throw new Error(&#039;Failed to load JSON object.&#039;);
	Array.prototype.toJSON = new JScript.Function(&quot;return Array.apply(null,this)&quot;);
	return {
		stringify:function(){
			try {
				return JSON.stringify.apply(null,arguments);
			} catch(e){}
			throw new Error(e.description);
		},
		parse:function(){
			try {
				return JSON.parse.apply(null,arguments);
			} catch(e){}
			throw new Error(e.description);
		}
	}
})();

var obj = {
	a: {
		b: 42,
		c: [1, 2, 3],
		d: [
			{
				a:1,
				b:[{
					e:1
				}]
			}
		]
	}
};

obj = JSON.stringify(obj,null,&#039;\t&#039;);

WSH.Echo(obj);
</code></pre></div><p>Но ещё надо бы &quot;запилить&quot; фикс на replacer и reviver, но..... пока чёт лень как-то. <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /> Пускай ещё кто-нибудь покреативит.</p>]]></description>
			<author><![CDATA[null@example.com (Xameleon)]]></author>
			<pubDate>Wed, 24 Feb 2021 18:16:41 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=146487#p146487</guid>
		</item>
		<item>
			<title><![CDATA[Re: JS: забавный способ работы с JSON]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=146481#p146481</link>
			<description><![CDATA[<p><strong>Rumata</strong>, понял. Согласен. </p><p>Немного подумал. В принципе, можно сделать такой фикс, наверное ? Я JS плохо знаю. Наверняка можно грамотнее решить, но пока только такой вариант пришёл в голову.</p><div class="codebox"><pre><code>
var JSON = (function(){
	var document = new ActiveXObject(&#039;htmlfile&#039;);
	document.write(&#039;&lt;meta http-equiv=&quot;x-ua-compatible&quot; content=&quot;IE=Edge&quot;&gt;&#039;);
	var JScript = document.Script,
		JSON = JScript.JSON;
	
	function patch(object){
		for(var i in object){
			if(typeof object[i] == &#039;object&#039;){
				if(object[i] instanceof Array) {
					var array = new JScript.Array();
					array.push.apply(array,object[i]);
					object[i] = array;
				}
				patch(object[i]);
			}
		}
		return object
	}
		
	return {
		stringify:function(value, replacer, space){
			try {
				if(typeof value === &#039;object&#039;) value = patch(value);
				return JSON.stringify(value, replacer, space);
			} catch(e){}
			throw new Error(e.description);
		},
		parse:function(text, reviver){
			try {
				return JSON.parse(text, reviver);
			} catch(e){}
			throw new Error(e.description);
		}
	}
})();

var obj = {
	a: {
		b: 42,
		c: [1, 2, 3],
		d: [
			{
				a:1,
				b:[{
					e:1
				}]
			}
		]
	}
};

obj = JSON.stringify(obj,null,&#039;\t&#039;);

WSH.Echo(obj);

</code></pre></div>]]></description>
			<author><![CDATA[null@example.com (Xameleon)]]></author>
			<pubDate>Wed, 24 Feb 2021 09:52:51 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=146481#p146481</guid>
		</item>
		<item>
			<title><![CDATA[Re: JS: забавный способ работы с JSON]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=146480#p146480</link>
			<description><![CDATA[<div class="quotebox"><cite>Xameleon пишет:</cite><blockquote><p>типа ActiveXObject</p></blockquote></div><p>Неточно выразился. Правильнее будет сказать, &quot;экземпляр типа ActiveXObject&quot;. Хотя и эта формулировка спорная. Все дело в <strong>new ActiveXObject(&#039;htmlfile&#039;)</strong>, который и порождает объект. Если посмотреть на него с этой стороны, то <strong>html instanceof ActiveXObject == true</strong>. Ну и отсюда все остальное вытекает: все вложенные объекты тоже порождены от ActiveXObject.</p>]]></description>
			<author><![CDATA[null@example.com (Rumata)]]></author>
			<pubDate>Wed, 24 Feb 2021 09:34:18 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=146480#p146480</guid>
		</item>
		<item>
			<title><![CDATA[Re: JS: забавный способ работы с JSON]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=146479#p146479</link>
			<description><![CDATA[<div class="quotebox"><cite>Rumata пишет:</cite><blockquote><p>На форуме DosTips увидел прикольный способ работы с JSON:</p></blockquote></div><p>У нас на форуме он уже давно гуляет в темах. ) </p><div class="quotebox"><cite>Rumata пишет:</cite><blockquote><p>Все бы хорошо, но все объекты типа ActiveXObject, что значит, что объекты (массивы в том числе)</p></blockquote></div><p>Почему уверенность, что именно &quot;типа ActiveXObject&quot;. Я бы сказал, что просто как Object</p><p>Да, есть такая проблемка. Причина понятна. Для движка JS массивы являются объектами. Но отличать массивы от объектов он может только в пределах себя. Т.е если массив создан внутри движка, то проблем нет. Собственно именно по этой же причине и происходит появление &quot;лишних&quot; элементов в массиве, которые являются методами.</p><p>Я фиксил так:</p><div class="codebox"><pre><code>
var document = new ActiveXObject(&#039;htmlfile&#039;);
document.write(&#039;&lt;meta http-equiv=&quot;x-ua-compatible&quot; content=&quot;IE=Edge&quot;&gt;&#039;);
var JScript = document.Script,
	JSON = JScript.JSON;

var obj = {
	a: {
		b: 42,
		c: new JScript.Array(1, 2, 3)
	}
};

WSH.Echo(obj.a.c.join(&#039;;&#039;));

obj = JSON.stringify(obj,null,&#039;\t&#039;);

WSH.Echo(obj)
</code></pre></div><p>Возможно <strong>JSman</strong> сможет нам что-то подсказать.</p>]]></description>
			<author><![CDATA[null@example.com (Xameleon)]]></author>
			<pubDate>Wed, 24 Feb 2021 09:05:03 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=146479#p146479</guid>
		</item>
		<item>
			<title><![CDATA[JS: забавный способ работы с JSON]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=146456#p146456</link>
			<description><![CDATA[<p>На <a href="https://www.dostips.com/forum/viewtopic.php?p=63722#p63722">форуме DosTips</a> увидел прикольный способ работы с JSON:</p><div class="codebox"><pre><code>
var html = new ActiveXObject(&#039;HTMLFile&#039;);
html.open();
html.write(&#039;&lt;html&gt;&lt;head&gt;&lt;meta http-equiv=&quot;x-ua-compatible&quot; content=&quot;IE=9&quot; /&gt;&lt;/head&gt;&lt;/html&gt;&#039;);
html.close();

var JSON = html.parentWindow.JSON;

var obj = {
	a: {
		b: 42,
		c: [ 1, 2, 3 ]
	}
};

var str = JSON.stringify(obj);
// {&quot;a&quot;:{&quot;b&quot;:42,&quot;c&quot;:{&quot;0&quot;:1,&quot;1&quot;:2,&quot;2&quot;:3,&quot;hasOwnProperty&quot;:{},&quot;length&quot;:3},&quot;hasOwnProperty&quot;:{}},&quot;hasOwnProperty&quot;:{}}

var obj2 = JSON.parse(str);
// [ActiveXObject]
</code></pre></div><p>Все бы хорошо, но все объекты типа ActiveXObject, что значит, что объекты (массивы в том числе) можно только перебрать в циклах for и for in. При переборе циклом for in &quot;вылезают&quot; &quot;лишние&quot; свойства, которые обычно не выводятся: length у массивов и hasOwnProperty у всех объектов. А еще у массивов отсутствуют собственные методы. То есть нельзя, например, вызвать obj2.a.c.join(&#039;-&#039;).</p>]]></description>
			<author><![CDATA[null@example.com (Rumata)]]></author>
			<pubDate>Sun, 21 Feb 2021 23:26:22 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=146456#p146456</guid>
		</item>
	</channel>
</rss>
