Console log from within json array - javascript

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?

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')})()
}

Related

Simple logic-engine in PHP for limited editorial programming

I am developing a system that is based on a lot of filters. I get an input, and the input needs to be sanitised. We have already build a large system for sanitation, that has a lot of logic inside it, however we wish to simplify this and make it more agile.
A very simple example: A filter could be, that we get in a feed that contains the words "Boat" "Boaat" "BoAt" and "boat". They should all be mapped to the same entity "boat" in our database.
Now, what we has been looking for, is a way to run very limited javascript, lua, python, anything - inside PHP, without the use of PECL or new binaries for PHP. With this our editors could do something like, very conditional (in JS):
var r = VALUE.toLowerCase();
if (r=="boaat")r="boat";
return r;
These examples of filters above are -very- simple, and are just to simply what we are looking for.
I would like to keep out of the way of anything that renders down to a simple PHP eval.
So simple question: When wanting a simple logic/scripting-engine inside PHP, that can be executed, with the options to manually insert the "variable environment", what are my options?
Why not collect your words in an object and get the normalized word out of it with an access by a lower case word.
{
boat: 'boat',
boaat: 'boat'
}
Access
word = words[string.toLowerCase()];

Recieving high volume data in client browser using Jquery / JavaScript

I am in the process of making a WordPress based application where a student can take the examination on his web-browser. The questions will be randomly selected and served from the question bank stored in a WordPress CMS.
In this regard following is important to share:
-each examination can have as many as 100 multiple choice questions.
-Each question can have images, each choice can have associated images.
-since the examination is time bound I can not send request to server every time the student completes his question.
My query is :
How do I send the questions from the server:
-should I send the whole question set in one go and then have the Java Script parse all the questions and choices parsed at the client side
or
-should the client repeatedly request the questions from server in the background in the chunks of say 5 question each, for example. If this is better approach I am not sure how do I implement this. Any pointers?, please.
Or is there a third approach which I am not aware of.
Please advise for any comments and solutions for the problem.
Thanks in advance.
Depends on user's selection,send appropriate JSON data to client and render it dynamivally,but if you want to use XML then lets talk about it:
I should mention that this comparison is really from the perspective of using them in a browser with JavaScript. It's not the way either data format has to be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.
JSON is both more compact and (in my view) more readable - in transmission it can be "faster" simply because less data is transferred.
In parsing, it depends on your parser. A parser turning the code (be it JSON or XML) into a data structure (like a map) may benefit from the strict nature of XML (XML Schemas disambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:
myJSON = {"age" : 12,
"name" : "Danielle"}
The parser doesn't need to be intelligent enough to realise that 12 represents a number, (and Danielle is a string like any other). So in javascript we can do:
anObject = JSON.parse(myJSON);
anObject.age === 12 // True
anObject.name == "Danielle" // True
anObject.age === "12" // False
In XML we'd have to do something like the following:
<person>
<age>12</age>
<name>Danielle</name>
</person>
(as an aside, this illustrates the point that XML is rather more verbose; a concern for data transmission). To use this data, we'd run it through a parser, then we'd have to call something like:
myObject = parseThatXMLPlease();
thePeople = myObject.getChildren("person");
thePerson = thePeople[0];
thePerson.getChildren("name")[0].value() == "Danielle" // True
thePerson.getChildren("age")[0].value() == "12" // True
Actually, a good parser might well type the age for you (on the other hand, you might well not want it to). What's going on when we access this data is - instead of doing an attribute lookup like in the JSON example above - we're doing a map lookup on the key name. It might be more intuitive to form the XML like this:
<person name="Danielle" age="12" />
But we'd still have to do map lookups to access our data:
myObject = parseThatXMLPlease();
age = myObject.getChildren("person")[0].getAttr("age");

Parse Javascript To JSON Using Python 3

this is a very specific request, and for that i apologise, but i am at a loss for what to do..
for a javascript project i am working on i want to be able to parse javascript with python and i found this implementation`port of the original narcissus called pynarcissus:
https://github.com/jtolds/pynarcissus
the problem for me is the information is buried in the python class structure.. something with which i am only vaguely competent.. and i want the output to be in JSON
i have tried to mine the data out but each time the JSON is invalid
my question is how would you go about doing something like this? i'd appreciate any specifics because the project contains nested classes of disparate types creating what seems to be a wholly unique problem
here are my attempts:
i took the return value for parse() and created a function that descends through the class structure returning values based on their type: 'str', 'int', 'bool', 'NoneType', 'list', 'dict', 'main.Node', 'main.Tokenizer', 'main.Object'; but the returned object is missing some properties in the classes, ie 'type', while retaining others like 'type_', also tokenizer always contains the same values
i took the output of the str function that the program prints to stdout, removed the clear and copy functions and the tokenizer: [object Object], then tried to manually add in double quotes where necessary to make the output a valid JSON object.. a few problems here, first off ignoring the tokenizer object seems like i am missing out on vital information, and the other problem was that sometimes there is "value" : "{" and sometimes there is "value" : { .. }, after completing the work the JSON was invalid
assuming the issue lied in the "value" : { .. } issue i resolved to add a new function identical the the str function but instead of printing just %s values, it would print \"%s\" where necessary.. now, i could differentiate between "value": "{" and "value" : "{ .. }" but i would have to go through and manually remove the quotes around objects.. after doing so the JSON was invalid
i've tried every copy'pasta solution for python class to json from the stacks but the nested aspect of the classes along with the changing types add complexity.. some properties lack a .dict even when the type is "class 'dict'" so the one'method'fits'all lambda solutions fail
for posterity:
once i massaged the code of pynarcissus to print json i found that the process fails on nested functions.. hilariously exactly the reason i stepped away from my homebrew method
in another thread(i) #firstfire suggested esprima and pyesprima
so i looked into the esprima suggestions, and after a bit of 2to3`ing and some more work returning valid json i got it working and so far it fits my needs perfectly
check out the issue, pull request, and fork:
issues : https://github.com/int3/pyesprima/issues/1
pr : https://github.com/int3/pyesprima/pull/2
fork : https://github.com/ghissues/pyesprima
(i) http://www.linuxquestions.org/questi....php?p=5364199
the old answer::
closed the issue and added a pull request
https://github.com/jtolds/pynarcissus/issues/6
you can check out the fork if you got here by looking for a way to parse javascript to json in python 3
https://github.com/ghissues/pynarcissus

Why and when do we need to flatten JSON objects?

I am surprised that no one on StackOverflow asked this question before.
Looking through the JSON object documentation and a quick google search did not yield satisfactory results.
What's the advantage of it? How does it work?
Edit: To make it clear, take a look at this flatten/un-flatten example.
Fastest way to flatten / un-flatten nested JSON objects
Thank you.
There are many situations where you get JSON text that was automatically built by some library. Throughout the programming languages, there are many libraries that build JSON text (one example is here).
Whenever libraries add some additional object or array wrappings, you might want to get rid of them maybe because you send the JSON to the server and your code there crashes because it expects a primitive value instead of an object (or an array). Or, if your JSON is a server response, you don't want the resulting Javascript code having to differ between object/array or not object/array. In all these cases, flattening is helpful as it will save you time. You will have to implement lesser if/elses, and you can reliably expect your data structure to be as flat as possible.
The other approach to improve code for the scenario mentioned is to write the code in a maximal robust way so there is no way for it to crash by superfluous wrappings ever. So always expect some wrappers and get it's contents. Then, flattening is not needed.
You see, it depends on what is building the JSON and what is parsing it. The building may be out of your scope.
This leads also to data model questions. I've worked with XML code that needed to be parsed quiet a different way if there where 0 entries of some XY, or if there were >0 entries of some XY. Having a wrapper that is allowed to have 0 or more entries of some XY will make live easier. These are data model desicions.
In all cases where the JSON represents an object structure that I've combined manually, I expect it not to change. So flattening something I've designed in detail would be disturbing. Standard operations as far I've seen them do not need flattening (e.g. JSON.stringify(), json_encode() etc.)
Here's a simple scenario: In a web app you have an HTTP POST that is updating a complex relational object.
POST
update=1
&user.id=12345
&user.email=testmail#domain.tld
&user.profile.name=Mr. Test
&user.profile.age=42
&user.profile.friend.0.email=tom#domain.tld
&user.profile.friend.1.email=sally#domain.tld
&user.profile.friend.2.email=bob#domain.tld
&user.profile.skill.0.id=100
&user.profile.skill.0.name=javascript
&user.profile.skill.1.id=200
&user.profile.skill.1.name=piano
Everything is already in a flat structure, so why not have a simple one-to-one binding? If you had a list of constraints or security requirements that you needed to enforce you could validate them by searching directly on the sorted key list.
Flat structures are easier for people to understand and work with there's even some cross-over with database de-normalisation. It also allows for context specific security and constraints to be implemented in a readable, but more verbose way.
When showing a user's view in full you may want to hide the display of the primary key ID for the user's list of skills.
"user.profile.skill.#.id": { hidden: true, readonly: true }
But when looking directly at a skill (to possibly edit it as an administrator) you may want to see the ID.
"skill.id": { readonly: true }
If you were writing a user-centric/self-service type CMS application you'd get more users on board and able to contribute using a straightforward flat model (flat abstraction of the underlying nested relational model) than you would with just the nested model.
TLDR: Flat is easier to read than nested. While programmers can handle nested schemas, recursive parsing and processing; end-users and admins usually prefer that part abstracted away.
I realize this is a 5 year old question at this point, but I figured, I'd add my thoughts to it, in case someone runs into a similar use case and finds this useful.
One of the use cases why you would want to flatten a JSON object, is for dynamic template binding via Regular Expression (RegEx) string interpolation. Well wasn't that a mouthful 👀😅? It simply translates to "template filling a string without hardcoding".
Ok Imagine a scenario, you have a template string like this for an email:
Hello {{firstName}},
It is amazing you chose to join our site. We are happy to have you on board.
To get started, we would really love it if you can confirm your email address
by clicking on the link: {{confirm_url}}.
Welcome aboard
The Team!
Given the following JSON object in memory:
{
"user" : {
"prefix" : "Dr.",
"firstName" : "Awah",
"lastName" : "Teh",
"email" : "awah#superduperubercoolsite.com",
"address" : {
"street": "100 Main St",
"city" : "PleasantVille",
"state" : "NY",
"phone" : "+1-212-555-1212"
}
},
"meta" : {
"confirm_url" : "http://superduperubercoolsite.com/confirm/ABC123"
}
}
it seems super simple to do a Regular Expression replace like so (assuming our email template string was stored in a variable named template and the json object was stored in a variable called templateData:
template = template.replace(new RegExp('{{firstName}}', 'g'), templateData.user.firstName);
template = template.replace(new RegExp('{{confirm_url}}', 'g'), templateData.meta.confirm_url);
Easy right? --> Actually yes! How about this email had 10 templated fields, or you wanted to decouple the template from the code, by storing it in a separate system like SendGrid, where your cool head of marketing can access the template and make changes to the copy-language, without having to call someone from engineering to make changes to the code, test the code and redeploy to production (what a hassle).
This is exactly where flattening of the JSON comes save the day!
Now there are many ways to flatten JSON, I have attached a link to a codepen I wrote that has logic to flatten JSON (actually, I demonstrate two similar but different approaches in the methods flattenJSONIntoKVP and flattenJSONIntoRAW check 'em out!).
That said, there are other implementations out there, and it is worth remembering that the focus on this post is to discuss the WHY JSON flattening could be useful, not the HOW.
Moving on! Assume you flattened the JSON from above (using my implementation that results in key value pairs) to something like this:
[
{ "key": "user.prefix", "value": "Dr."},
{ "key": "user.firstName", "value": "Awah"},
{ "key": "user.lastName", "value": "Teh"},
{ "key": "user.email", "value": "awah#superduperubercoolsite.com"},
{ "key": "user.address.street", "value": "100 Main St"},
{ "key": "user.address.city", "value": "{PleasantVille"},
{ "key": "user.address.state", "value": "NY"},
{ "key": "user.address.phone", "value": "+1-212-555-1212"},
{ "key": "meta.confirm_url", "value": "http://superduperubercoolsite.com/confirm/ABC123"},
]
Now, my friend, you are cooking with GAS!
Why, cause now you can dynamically interpolate the template string with values from the JSON object without giving too much worry to the structure of the JSON (if it changes due to the application evolving, you don't have to also remember to come down here and change this interpolation code -- you simply just have to update the email template itself, which mind you, is on SendGrid [per this example]).
So how to do it you say?: Simple, iteratively. Let's assume that flattened from above was stored in a variable called flatJSON:
///Notice how I use Javascripts native string interpolation to create my RegExp
///Also note that I am replacing the dot (.) in my flattened JSON variable names with a double underscore (__), I only do this because my intended target is SendGrid, and I don't believe it likes dots in its template placeholders.
flatJSON.forEach(kvp=>template = template.replace(new RegExp(`{{${kvp.key.replace(/\./g, '__'}}}`, 'g'), kvp.value));
That's it, one line of code to replace possibly 10 or even hundreds or even thousands (ok.. maybe not thousands, but you get the point).
Ohh! almost forgot, we need to update our template string.
Notice how now, in our new templated string we can use a somewhat FQDN style variable to map back to our original JSON (Ideally if SendGrid supported dots in their template placeholders, this would look super sweet but alas, can't always win everything!😭.
Hello {{user__firstName}},
It is amazing you chose to join our site. We are happy to have you on board.
To get started, we would really love it if you can confirm your email address
by clicking on the link: {{meta__confirm_url}}.
Welcome aboard {{user__prefix}} {{user__lastName}}!
The Team!
Et Voila!
Just like that, we have accomplished some good here today; we have:
Answered the WHY of flattening JSON objects
We dibble-dabbled into the how, with the codepen example
And we even overviewed a use case where taking advantage of JSON flattening can help you write durable dynamic code, that evolves as your underlying object structures change -- and that doesn't require you to leverage the big bad ugly eval method (we can talk about big bad ugly eval on another post).

A good way to implement a string tokenizer ( or use one that's already established )

Found myself in a situation where I was making one of two rookie mistakes:
Writing code that I should get out of a library
Writing super complex code that could be greatly simplified using better patterning
What I'm trying to do is pretty simple, I need to send instructions to some JavaScript code that prints fields from an object to the page. Things started out fine, the following string:
message, tags, date
Easily instructed the code to get these elements from the object using
field_array = instruction_string.split(',')
obj['message'], obj['tags'], obj['date']
Then I realized that I wanted to modify that date field to reflect the time zone I was in. Enabling the string to carry special instructions for a field added a little complexity with regex, but still wasn't too complicated:
message, tags, date(GMT-5)
Using the code:
var special_instruction = /\(.*\)/ig.exec('date(GMT-5)')[2]
RESULT: special_instruction = 'GMT-5'
I realized that I was getting in over my head when I realized that I also wanted to tell the output to adjust the date so that it reflects the time delta since right now instead of printing the actual date:
message, tags, date(GMT-5_)(SINCE_NOW)
The regex that I wrote didn't work:
var special_instruction = /\((.*)\)/ig.exec('last_updated(GMT-5)(since_now)')
RESULT: special_instruction = 'GMT-5)(since_now'
Although there is probably a way to fix the regex, this indicates that I should be using a tool or established pattern to do this instead of writing custom code off the cusp and screwing around with it for way too long.
Are you sure you want to use strings and regular expressions for this?
An alternative would be to use an array and objects for defining the fields that should be printed.
Something like this:
var fields = [{
name: 'message'
}, {
name: 'tags'
}, {
name: 'date',
timezone: 'GMT-5',
since: new Date() // now
}];
For getting the values from that sure be printed you can iterate over the array and look for the name field. If you found an object with name date you can look for additional properties. You could also add new properties very easily.

Categories