parsing json file - scan and separate its attributes - javascript

I am trying to parse json file to match name of the user
var jsObj = eval('('+request.responseText+')');
var name = document.getElementById("name");
for(var i=0;i<jsObj.names.length;i++)
{
alert(jsObj.names[i].value);
if(name.value==jsObj.names[i].properties['name'])
{
//do additional stuff
}
}
I have a simple JSON file but I get error as cannot read property name of undefined or null
I also tried just jsObj.names[i].name still the error persists. If I alert names[0] etc I get object...
EDIT: My JSON file
{
"names":[
{
"name": "vcjndjvndfjv",
"address": "jnvdfjnvdjn",
"country":""
},
{
"name": "vcjndjvndfjv",
"address": "jnvdfjnvdjn",
"country":""
},
{
"name": "vcjndjvndfjv",
"address": "jnvdfjnvdjn",
"country":""
}
]
}
I have changed the actual values of the attribs but it looks like this..
I have also tried JSON.parse but I think the error is related to jsObj.names[i].name
Where am I going wrong?

try this:
var jsObj = JSON.parse(request.responseText)

Related

Issue with accessing jinja python list in javascript

I have a python list called "devices" that looks something like this:
[{
'Version': 'V14E',
'DeviceID': 'e00fce68281671574f416a8c',
'TerminationDate': '2050-12-31',
'Latitude': 31.322139613573903,
'ActivationDate': '2021-01-04',
'Longitude': -101.93960164357534,
'DeviceName': 'Hans_Gruber-1'
}, {
'Version': 'V14E',
'DeviceID': 'e00fce68e1265e12e12fa02a',
'TerminationDate': '2050-12-31',
'Latitude': 31.32151602493975,
'ActivationDate': '2021-01-04',
'Longitude': -101.93948944894449,
'DeviceName': 'Hans_Gruber-2'
}]
In my flask app, I pass this list to my html file by the name "devices_test" using json.dumps() to correctly format the data to be used in java script.
return render_template("json_form.html",
devices = devices, components = components, operator = operator, name = site_name,
devices_test = json.dumps(devices))
Here is me trying to test out an answer I have seen on another post here via the "data" variable:
function update_device_form(strDevice) {
var data = {
{
devices_test | safe
}
};
var device_index = document.getElementById("devices").selectedIndex;
if (device_index == 0) { //IOW if no device is selected
document.getElementById("device_id").value = "";
} else {
document.getElementById("device_id").value = '';
}
But I get errors such as "Declaration or statement expected" and "Property assignment expected" and "',' expected". What am I doing wrong here?
You can use string to remove the error var data = "{{devices_test|safe}}"
Now data is not javascript object, it is a string, you need to use JSON.parse and also replaceAll.
var data = "{{devices_test|safe}}"
var data = data.replaceAll("'",'"') // replace single quote to double
var data = JSON.parse(data)
one line
var data = JSON.parse("{{devices_test|safe}}".replaceAll("'",'"'))

Adding nested arrays in JSON file using node.js

I am fairly new to Javascript and nodejs. I would like a JSON file (results.json) that takes the format of something similar to this:
Starts off as:
{
"name":"John",
"task":[]
}
then eventually becomes something like this with nested arrays:
{
"name":"John",
"task":[ ["task1","task2"], ["task3", "task4"] ]
}
I want to push to the "task" array a new list of tasks (always of size 2) everytime something is done (in my case when a form is submitted with a button-press).
So for example, after another "action", the JSON file will look something like this:
{
"name":"John",
"task":[ ["task1","task2"], ["task3", "task4"] , ["task5", "task6"] ]
}
NOTE: "task(1,2,...,6) was just used as an example, these will be other strings corresponding to the form submission.
This is what I have so far in my server-side file:
var fs = require('fs')
app.post("/addtask", function(req, res) {
fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data)
var newTask1 = req.body.newtask1
var newTask2 = req.body.newtask2
//WHAT DO I PUT HERE
fs.writeFile("results.json", JSON.stringify(json))
})
});
Please do correct me if my syntax is wrong or if my idea of how a JSON file works is wrong.
Just push the data as an array
var resObj= {
"name":"John",
"task":[]
}
var newTask1 = "task1";
var newTask2 = "task2";
resObj.task.push([newTask1,newTask2]);
console.log(resObj);

AJAX - Parse JSON object returned in JQUERY

I stucked a little bit in here>
My php script returns this JSON (in variable response) (encoded array with json_encode) :
{"1":{"id":"pvv001","tooltip":"tip1","link":"http:\/\/domain\/file1.html"},"2":{"id":"pvv002","tooltip":"tip2","link":"http:\/\/domain\/file2.html"}}
I hope this is valid JSON object ...
Then here is JavaScript function which should get this string and process it - load to ELEMENT "id" a content of "link".
function jLinks(idchapter)
{
var url = 'ajax_loadlinks.php';
var data = {
idchapter : idchapter
};
$.post(url,data, function(response)
{
//$('#coursecontent').html(response);
var obj = JSON.parse(response);
for (var i=0; i<obj.length; i+1)
{
$('#'+obj[i].id).html('link');
}
});
}
It is not throwing any error in browser or console, but elements are not updated at all.
I quess my parsing and accessing data is wrong somehow, but I have no idea how to debug.
As your string is an object not array, so you need $.each method to loop over each key of object.
var obj ={
"1": {
"id": "pvv001",
"tooltip": "tip1",
"link": "http:\/\/domain\/file1.html"
},
"2": {
"id": "pvv002",
"tooltip": "tip2",
"link": "http:\/\/domain\/file2.html"
}
};
$.each(obj,function(i,v){
$('#'+v.id).html('link');
});
Fiddle
please try this
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.log(obj[prop].id);
$('#'+obj[prop].id).html('link');
}
}

Protractor data driven - Is displaying 'undefined' when I try to print JSON file

I'm working with protractor and I'm trying to implement data driven.
I'm using this code that I found searching in google.
This is my test.json
{
"username":"testusername"
}
And i'm calling this json from my spec and trying to print in console:
var fs = require('fs');
var content = fs.readFileSync('test/e2e/tests/test.json');
console.log(content.username);
The test is not failing but in the console is print undefined
enter image description here
I'm missing something? or i'm not implementing well the json?
Hope you can help me.
You just need to do require(json_file_path). It will work. Try below code.
var content = require('test/e2e/tests/test.json');
console.log(content.username);
You are not parsing the JSON. readFileSync does read the file as a string. So content is a string containing the JSON, not an Object.
The solution is to simple use JSON.parse:
var content = JSON.parse(fs.readFileSync('test/e2e/tests/test.json'));
Try this solution.
On Main spec:
var testData = require('./Data.json');
describe('...', function() {
testData.forEach( function (data) {
var strUser = data.strUser;
var strPass = data.strPass;
it('...', function() {
<code here>
});
});
});
On Data.json (which is located on same folder as Main spec):
[{
"strUser": "user1",
"strPass": "pass1"
},
{
"strUser": "user2",
"strPass": "pass2"
},
{
"strUser": "user3",
"strPass": "pass3"
}]
Hope it helps :)

JSON parsing with JsonResult and JavaScript

Environment: ASP.net MVC:
Given anonymous structure as such:
var test = new {
name = "me",
age = "100"
};
that then gets parsed as
result = Json(test)
data = result.Data // Comes back with { name = "me", age = "100" }
Which then gets successfully passed into a JS function, how do I go about using that as a JSON object, so that I can do something like
function(data) // Where data = { name = "me", age = "100" } or similar
{
var name = data.name // "me"
}
Try
var object = eval('(' + data + ')');
then you should be able to do object.name.
The JSON is invalid, it should be
{
"name" : "me",
"age" : "100"
}
And new {..} doesn't do anything meaningful -- the object literal is alone sufficient.

Categories

Resources