Javascript innerHTML and JSON parsed string difference - javascript

I use JSmart (SMARTY JS port) in my project. I have two options to obtain the template:
insert it inside
<script id="tpl" type="text/x-jsmart-tmpl">
...
</script>
and pull it by
document.getElementById('tpl').innerHTML
receive it in JSON value
I met an issue with the second option: item value after JSON.Parse contains special chars like \r \n or \t, includng / etc. JSmart does not undestand this.
In case of pulling from innerHTML the result string handled fine.
Small example:
JSON parsed value:
<!-- \r\n SMARTY template\r\n\tdata object\r\n
innerHTML pulled value:
<!--
SMARTY template
data object
How I could convert JSON parsed value to the string equal I got from innerHTML?

The template file is not JSON, is a smarty template. However, you can fetch it from a file/url like this:
$.get("template_url", function(tplText) {
var tpl = new jSmart( tplText );
//Compile the tpl with your data object
var res = tpl.fetch( data );
//res is your compiled HTML
//document.write( res );
});
Demo: https://jsfiddle.net/iRbouh/3wpfu604/

Related

How to send results from bash script (JSON format) into Javascript array variable (html file)?

My goal is to create simple search filter by name in html/javascript for data that I am getting from API in JSON format. In bash script I already formatted data so it is in right format for me to filter it later in javascript:
Data ready to be pushed/imported into let jsonData array (inside html file) from data file (example.json):
{"name":"vnode","address":"10.19.110.51","group":"windows","responsible":"Alen"},
{"name":"vnode2.izum.pri","address":"10.1.30.100","group":"windows","responsible":"Mario"},
{"name":"vnode3","address":"10.19.110.52","group":"windows","responsible":"John"}
I want to send this data from example.json and insert it into jsonData array inside javascript (index.html), How do I do it?
This is inside index.html:
<script>
let jsonData = `[
**DATA GOES HERE**
]`
function search_server() {
let input = document.getElementById("myInput").value;
input = input.toLowerCase();
let x = document.querySelector("#myUL");
x.innerHTML = "1";
for (i = 0; i < data.length; i++) {
let obj = data[i];
if (obj.name.toLowerCase().includes(input)) {
const elem = document.createElement("li");
elem.innerHTML = `${obj.name} , ${obj.address} , ${obj.group} , ${obj.responsible}`;
x.appendChild(elem);
}
}
}
</script>
I managed somehow to insert results from bash to html, but I only managed to do it into div class:
Method for sending bash results from file into div class element:
reg='<div class="content-middle">'
while IFS= read -r line; do
printf '%s\n' "$line"
[[ $line =~ $reg ]] && cat /usr/share/inventory/data.txt
done < /usr/share/inventory/indextemplate.html > /usr/share/inventory/index.html
So here is where I managed to send data:
<div class="content-middle">
</div>
No success on trying it to send into javascript:
reg='let jsonData = `['
while IFS= read -r line; do
printf '%s\n' "$line"
[[ $line =~ $reg ]] && cat /usr/share/inventory/data.txt
done < /usr/share/inventory/indextemplate.html > /usr/share/inventory/index.html
I don't have much knowledge on BASH but I think I have a solution.
First use BASH script to write a JS file, then place file in your project folder.
Insert your JS code in the empty JS file with BASH.
Use BASH to read your data file (example.json) to put the data in your JS file.
Good luck
I was able to do it with command AWK:
I created string to replace, in my example ****
Then i read file example.json, replace **** with content from example.json into new file bakka.html
With command:
awk 'FNR==NR{s=s"\n"$0;next;} /[*][*][*][*]/{$0=substr(s,2);} 1' '/usr/share/inventory/example.json' '/usr/share/inventory/index.html' > '/usr/share/inventory/bakka.html'
Thank you
Lawrence Cherone
If I have understood correctly, you have retrieved and parsed the data required into JSON-formatted objects saved in a file named example.json, and you now wish to assign the data to a variable within your html page so that it may be read and used by javascript in the page. (I will proceed on that basis so apologies if I have misunderstood).
The easiest way to make the data available is to include it in an expression, which will assign it to a named variable, at the time the file was written and to include the file by naming it with a .js, extension and reference it in a script tag from within the html (before the script that will make use of it).
First however, you will have to slightly modify the format of the JSON. Currently, your JSON data is arranged as three object notations, separated by commas:
current data format (in example.JSON):
{ -- 1st -- },
{ -- 2st -- },
{ -- 3st -- },
Such a structure has no meaning in javascript. If you examine JSON fetched with a typical api, it will usually list the object structures as elements of an array. If you reformat that file when you build it, you can make it so it is ready to use:
suggested format for exmaple.js:
const JSONdat = `[{"name":"vnode","address":"10.19.110.51","group":"windows","responsible":"Alen"},
{"name":"vnode2.izum.pri","address":"10.1.30.100","group":"windows","responsible":"Mario"},
{"name":"vnode3","address":"10.19.110.52","group":"windows","responsible":"John"}]`
Note the use of back ticks to avoid conflict with quote marks, and the presence of square brackets enclosing the data list. Note also, the value of JSONdat is a string, not an array nor objects (this is the purpose of JSON, to transport data as strings)
Next, in the html, load the file as a regular script (can be in the header, must be before the data is used):
html:
<script src="example.js"></script>
The JSON string is now available to JS in your document by referencing the name you gave it (JSONdat in the example above). The variable JSONdat has global scope and is available to javascript of any scope that loads later in the document.
To be able to iterate the array and read the object data, the JSON string has to first be parsed to make it an actual javascript array of objects:
const objectArray=JSON.parse(JSONdat)
objectArray now contains valid javascript objects inside a valid javascript array, which can be iterated as you wish to use the object data.
Working example:
const JSONdat = `[{"name":"vnode","address":"10.19.110.51","group":"windows","responsible":"Alen"},
{"name":"vnode2.izum.pri","address":"10.1.30.100","group":"windows","responsible":"Mario"},
{"name":"vnode3","address":"10.19.110.52","group":"windows","responsible":"John"}]`
// that variable will be available if the file holding it was loaded as a the src attribute of a regular script element.
const objectArray = JSON.parse(JSONdat);
console.log(objectArray[1].address);
// reports the value associated with the address key in the second object;

Python Dictionary Object Conversion to JSON when Output Through Template

I am using the Flask framework to obtain a dictionary object with the key set to the user ID and the value set to the username. From the view in Flask I am converting it to json using jason.dumps and when rendering the template, outputting direct to the Javascript code for example:
<script type="text/javascript">
var = {{ users }};
...
</script>
When I examine the rendered HTML code the string value outputted looks as below, example given for one user:
var = {"5d626ba11c9d4400004665b5": "shears"};
As you can see it is encoding the quote characters to their character value. How do I get this to output as a JSON object in the Javascript?
You could render a template variable inside a string, unescape HTML and then parse the result as JSON.
function unescapeHtml(safe) {
return $('<div />').html(safe).text();
};
var usersDict = JSON.parse(unescapeHtml('{{ users }}'));
The usersDict variable is an object:
Object { 5d626ba11c9d4400004665b5: "shears" }
Hope this helps.

get php array in javascript (laravel)

I want to pass php array in javascript code . when i use like this:
var resData = "{{ json_encode($data['calendarItems']) }}";
or this :
var resData = "{{ $data['calendarItems'] }}";
in both the result is :
[{"title":"rfvd vc","expired_at":"2018-12-31 00:00:00"}] //formatting
and JSON.parse return error. I can not get the array
There's two issues here. The first is that you're quoting the json output and the second is that the result is escaped to html entities.
Remove the quotes and output the result in raw format:
var resData = {!! json_encode($data['calendarItems']) !!};
Omitting the quotes around the result will remove the need to use JSON.parse(), since the variable will contain proper json from the start.
Read more about unescaped data in blade in the manual
When you do {{ }} it converts string elements inside into html entities. so { will be converted to "
I will suggest to use this package, which has cleaner implementation of passing data as usable js variables in your blade file.
You can try this:
var mapData = JSON.parse('<?php echo json_encode($latLng) ?>');
where $latLng is a PHP array.

How can I save & extract a json object as a string inside json from PHP to Javascript?

I'm trying to save a string which is encoded as json into another json string.
In particular, I have to be able to handle empty objects: "{}".
PHP:
$sVal = "{}";
$jsonString = "{\"Var2\":\"My first var\", \"Var2\":\"My second var\", \"MyBlankObject\":\"{}\"}"
...
Javascript:
var oMyJSON = JSON.parse('< ?= $jsonString;? >');
I get a JSON parse error saying an unexpected { was found.
I can see the code in Chrome's debugger.
The brackets are simply removed and in the client side (javascript ) code, the object is replaced with the word null. That's not valid JSON.
,"Properties":null,
This causes javascript to crash.
If I try to json_encode it on the server side (PHP) I get double quotes on each side of the brackets.
,"Properties":""{}"",
I get the same thing if I just add the double quotes: ""{}""
Of course, this causes javascript to crash too.
Once in the client and I have the JSON object intact, I need to be able to extract the 'string' held in the property: MyBlankObject and then decode that JSON into a seperate JSON object.
Everything I've tried fails. How can I accomplish this?
You can define the object using PHP notation, and let json_encode encode it for you.
$phpArray = [
'Var2' => 'My first var',
'Var2' => 'My second var',
'MyBlankObject' => new \stdClass
];
And then in the JavaScript:
var oMyJSON = JSON.parse('<?= json_encode($phpArray); ?>');

Passing (and parsing!) JSON objects through MVC4

I'm confused as to how I should be using JSON objects within MVC and how they should passed from Controller, to View, to Jscript.
I'm also not sure if I'm correctly parsing the JSON objects at the right points...
My controller is returning a PartialView with a json object ("Variables" is a list of data e.g. Id=2012, Name=BillyJoel, Value="£2,000"):
public ActionResult JavascriptConstants() {
var variables = Service.Obtain<VariableService>().All().ToList();
var json = new JavaScriptSerializer().Serialize(variables);
return PartialView("JavascriptConstants", json);
}
My View then makes this data available to my scripts by creating this variable:
#model string
...
var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))';
My Jscript file then accesses the data and attempts to pull out the information and key value pairs, but seems to be interpreting the JSON as a string:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
for (var variable in variableList) {
alert(variableList[variable]);
}
This just returns alerts of ", [, {, etc. as each character of the string is displayed. How do I access the key values of the JSON object?
I've tried changing my JS to use:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
But this just gives me an Uncaught SyntaxError: Unexpected token I error in my browser (I'm assuming when it hits the "I" of "Id).
Any help much appreciated, thanks.
I found the issue:
The issue was the use of JavaScriptSerializer().Serialize(foo) as this was creating a JSON object that contained newlines and tabs instead of replacing them with \n and \t.
$.parseJSON() cannot handle newlines and so throws up unexpected token error.
This was corrected by importing the JSON.NET package and using :
var json = JsonConvert.SerializeObject(variables);
This passed a JSON object with newlines and tabs replaced with \n's and \t's. Which can then be made accessible to the View using:
#model string
...
var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))';
and finally in the script using:
var variableList = $.parseJSON(mvcListOfVariablesInDB)
Hope this helps someone else one day...

Categories

Resources