JSON encode in Slim framework - twig

I am having problems sending a JSON encoded array to my view.
So I am doing this in my route
$data['values'] = array('name'=>'John');
$data['values'] = json_encode($data['values']);
return $this->view->render($res, 'githubpresentation.html', $data);
And in my view, in the script tag I do this
var values = "{{values}}" ;
console.log(values);
values = JSON.parse(values);
console.log(values);
The first console.log, before the JSON.parse outputs this:
{"name":"John"}
And when I do the JSON.parse I get an error, of course
Unexpected token & in JSON at position 1
Now I could do some sort of replace of the &quot, but do I really need to? Shouldn't I be able to send a JSON from the server?

This is related to the default escaping strategy. You can fix it by using the js one:
var values = "{{values|e('js')}}" ;
console.log(values);
values = JSON.parse(values);
console.log(values);
Output:
{"name":"John"}
Object {name: "John"}

Related

Encoding Text to Base64 and decoding back to JSON

I am trying to encode a text to Base64 and using NodeJS, and then while getting the data I am decoding it back from Base64. Now I need to change the data into JSON so I could fill the relevant fields but its not converting to JSON.
Here is my code:
fs.readFile('./setting.txt', 'utf8', function(err, data) {
if (err) throw err;
var encodedData = base64.encode(data);
var decoded = base64.decode(encodedData).replace(/\n/g, '').replace(/\s/g, " ");
return res.status(200).send(decoded);
});
In setting.txt I have the following text:
LENGTH=1076
CRC16=28653
OFFSET=37
MEASUREMENT_SAMPLING_RATE=4
MEASUREMENT_RANGE=1
MEASUREMENT_TRACE_LENGTH=16384
MEASUREMENT_PRETRIGGER_LENGTH=0
MEASUREMENT_UNIT=2
MEASUREMENT_OFFSET_REMOVER=1
This decodes the result properly but when I use JSON.parse(JSON.stringify(decoded ) its not converting to JSON.
Can someone help me with it.
Try below snippet
let base64Json= new Buffer(JSON.stringify({}),"base64").toString('base64');
let json = new Buffer(base64Json, 'ascii').toString('ascii');
What does base-64 encoding/decoding have to do with mapping a list of tuples (key/value pairs) like this:
LENGTH=1076
CRC16=28653
OFFSET=37
MEASUREMENT_SAMPLING_RATE=4
MEASUREMENT_RANGE=1
MEASUREMENT_TRACE_LENGTH=16384
MEASUREMENT_PRETRIGGER_LENGTH=0
MEASUREMENT_UNIT=2
MEASUREMENT_OFFSET_REMOVER=1
into JSON?
If you want to "turn it (the above) into JSON", you need to:
Decide on what its JSON representation should be, then
Parse it into its component bits, convert that into an appropriate data struct, and then
use JSON.stringify() to convert it to JSON.
For instance:
function jsonify( document ) {
const tuples = document
.split( /\n|\r\n?/ )
.map( x => x.split( '=', 2) )
.map( ([k,v]) => {
const n = Number(n);
return [ k , n === NaN ? v : n ];
});
const obj = Object.fromEntries(tuples);
const json = JSON.stringify(obj);
return json;
}

How do I access content from JSON string?

I am receiving a JSON object from the backend now I just want "result" array only in my template variable in my angular application from it.
{
"result":[
{"name":"Sunil Sahu",
"mobile":"1234567890",
"email":"abc#gmail.com",
"location":"Mumbai",
"Age":"19"
}
],
"status":200
}
Try with
variable_name["result"].
Try with
var data = response from the backend
var result = data.result;
$var = '{"result":[{"name":"Sunil Sahu","mobile":"1234567890","email":"abc#gmail.com","location":"Mumbai","Age":"19"}],"stats":200}';
If your $var is string, you need to turn it to "array" or "object" by json_decode() function
object:
$var_object = json_decode($var); //this will get an object
$result = $var_object->result; //$result is what you want to get
array:
$var_array = json_decode($var, true); //this will get an array
$result = $var_array['result']; //$result is what you want to get
Else if $var is object, direct use
$result = $var->result; //$result is what you want to get
As result is an array of objects, you can either use any loop to extract key value pair or you can directly access the array using index value.
var results = data["result"] // this would return an array
angular.forEach(results, function(value, key) {
//access key value pair
});
For accessing results in HTML, ng-repeat directive can be used.
Your question didn't explain further, but in the simple way try this :
const stringJson = `{
"result":[
{"name":"Sunil Sahu",
"mobile":"1234567890",
"email":"abc#gmail.com",
"location":"Mumbai",
"Age":"19"
}
],
"status":200
}`
const obJson = JSON.parse(stringJson);
console.log(obJson.result);

What is difference between get data from file and after parse data in byte?

I have some problems with the length in a byte of data get from a file. In my case, I use the readFileSync method to get data from a text file. But when I do something like the below code. It gives me 2 difference results.
let data = fs.readFileSync('size.txt');
console.log(data.length);
console.log(JSON.stringify(JSON.parse(data)).length);
Result in: 579859 (console log 1) and 409065 (console log 2)
So, I don't understand why the size is decreased after I parsed it to JSON and then I use the stringify method.
Thank you for any helping!
JSON.stringify will not restore the spaces like in the below example :
const obj = `{
"keyA": "obiwan kenobi",
"testB": "foo"
}`;
console.log(obj);
const obj2 = JSON.stringify(JSON.parse(obj));
console.log(obj.length, obj2.length);
console.log(obj2);

Convert the object into a string and bring in the necessary form

An object comes to me. I write the variable key and the value through the loop:
let update_info = [];
for (let[key, value] of Object.entries(req.body)) {
update_info.push(`${key} = ${value}`);
}
console.log(JSON.parse(update_info));
Output to console:
undefined:1
user_name = name,user_email = #email.com,user_password = 12345678,about = aboutaboutaboutabout
^
SyntaxError: Unexpected token u in JSON at position 0
Why it happens?
I need to be displayed in the console like this:
'user_name' = 'name','user_email' = '#email.com','user_password' = '12345678','about' = 'aboutaboutaboutabout
How do i implement this?
I've reproduced your code like this and all you need to do is
JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string.
JSON.parse turns a string of JSON text into a JavaScript object.
let obj = {
"welcome": "hello",
"reply": "hi"
}
let update_info = [];
for (let[key, value] of Object.entries(obj)) {
update_info.push(`${key} = ${value}`);
}
console.log(JSON.stringify(update_info));
Try the below code:
You need not to parse it using JSON.parse because the array is not yet stringified, so you should use toString() to achieve the desired result
let update_info = [];
for (let[key, value] of Object.entries(req.body)) {
update_info.push(`'${key}' = '${value}'`);
}
console.log(update_info.toString());
If you are interested in printing the Object key value pair in the console to have better view use
console.log(JSON.stringify(object, undefined, 2))
This will print the object in proper format indented by 2 spaces

NodeJS Query with MongoDB

I want to use add regex to my query in mongodb.
server.js
app.post('/form',function(req,res){
var tf = req.body.termFound;
var str1 ='"keyword":{$regex:/'+tf+'/i}';
db.collection('a').find({str1}).toArray(function (err,results){
if (err) return console.log(err)
res.render('stest.ejs',{arr:results})
});
For example if the termFound is LOOPS.
I wish to add the regex so that it will become non case sensitive, allowing me to find field values with (loops) or (loops,java)
"keyword":{$regex:/LOOPS/i}
Which is done from the line 3 code above.
However when i try to send it to my mongoDB for connection. I suspect it gives a different value. As i tried
var str1 ='"keyword":{$regex:/'+tf+'/i}';
var str3 ={str1};
res.send(str3);
i was return with
{"str1":"\"keyword\":{$regex:/LOOPS/i}"}
My final query should be something like
db.collection('a').find({"keyword":$regex:/LOOPS/i}).toArray(function (err,results)
I have experimented with JSON.parse(str1)
var str1 ='"keyword":{$regex:/'+tf+'/i}';
var filters = JSON.parse(str1);
db.collection('a').find(filters).toArray(function (err,results){
but was given
SyntaxError: Unexpected token : in JSON at position 9
at JSON.parse ()
I have spent days trying to fix this.. my question is how can i query do this with regex so as to make my search non case sensitive?
Edit: Managed to find out the answer. Had to use new RegExp() to create the reg exp object!
app.post('/form',function(req,res){
var tf=req.body.toFind;
db.collection('a').find({"keyword":new RegExp(tf,'i')}).toArray(function (err,results){
if (err) return console.log(err)
res.render('stest.ejs',{question:results})
})
});
You are so close here. Instead of trying to pass a string to your MongoDB find as you have above, just pass in the regex.
This way, you can use a template string or concatenate strings (such as '/'+tf+'/i').
UPDATE This method just mentioned won't work for all the reasons I'm getting ready to explain in the following paragraph regarding the original problem. This doesn't create an actual regular expression.
Previously, when you pass in a single string to the find function, Mongo starts looking for the key "str1" and seeing if it found a value of that string, whatever '"keyword":{$regex:/'+tf+'/i}' would evaluate to as a single string (note the surrounding single-quotes). You can't call JSON parse on this particular string because it is not a valid JSON encoded string. See an example below that should work better:
app.post('/form',function(req,res){
var tf = req.body.termFound;
// var reg =`/${tf}/i`; not an actual regex, still a string!!!
var reg = new RegExp(tf, 'i') // as you have since discovered
db.collection('a').find({"keyword": {$regex: reg }}).toArray(function (err,results){
if (err) return console.log(err)
res.render('stest.ejs',{arr:results})
});
})

Resources