Console log from within json array

Just playing around with a JSON array and wanted to know if it was possible to console log from directly within a JSON array. ie:

{ "id": "1", "type": "text", "description": "hello <script>console.log('console this text')</script> I am testing },

In the above example it will display the <script>console.log('console this text')</script> as text rather than as actual html. Any way to make this work to produce the message in console by placing it within the array?

Answers


That really depends on what you mean...

In straight JavaScript, you can use object notation in that way, but you really need to wrap it in a function call.

In addition to this, you are mixing javascript and loose text very badly... you really need to let the browser know which one you are using and when.

For example, those script tags? If you are already using JavaScript, then why tell the browser 'here is some script'?

With a little cleaning up:

var myObject = { 
    id: "1", 
    type: "text", 
    description: function(){console.log('console this text')}
}

myObject.description();

This is valid JavaScript and will run perfectly well in a browser if entered into the page this way.

However, I suspect that this isn't what you mean... what you intend to do is to pull this from an AJAX call, for example, and have it run arbitrary script within a browser.

That will not work.

JSON, used this way, is designed as a data format, and does not allow methods to be passed, only properties.

However, there are some uses where this type of behavior could be coaxed: LOOK HERE.

In short, ANY text, JSON or not, could be evaluated on a client system and could potentially run malicious code. This is very similar to security issues in PHP where poor programming practice allows the use eval and other exploits to run client fed code on the server.

This is why so many websites are neurotic in their scrubbing of any data which has been fed by an arbitrary user... scrubbing html tags and javascript code out of user comments, for example.


You can try using a self invoking function.

var obj = {
'a' : '1',
'b' : '2',
'c' : (function(){console.log('3')})()
}

Need Your Help

IIS 7 URL Redirect based on URL path

asp.net wcf iis iis-7 url-rewriting

I have a WCF Web Service hosted inside a ASP.NET 4 environment (IIS 7.5 on Windows 7), and I would like to use URL Rewriting / Redirection.

How to call a function on submit?

jquery html

I am not able to call jQuery on submit. The alert in the function is not displayed.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.