Hi i'm relatively new to JS and keep getting the error missing] after element list when I try and run the following:
Have a JSON file called test.JSON:
{
"156644": {
name: "name1",
"street": "street1",
"city": "city1"
},
"68656": {
"name": "name2 ",
"street": "street2",
"city": "city1"
},
"388655": {
"name": "name3",
"street": "street3",
"city": "city1"
},
"4564": {
"name": "name4",
"street": "street4",
"city": "city1"
},
"6333": {
"name": "name5",
"street": "street5",
"city": "city1"
}
}
And some Javascript:
var myObject = eval("(" + $.getJSON("test.json") + ")");
How can I fix this error?
The getJSON function:
Will parse JSON into a JavaScript object for you. Don't touch eval.
Is asynchronous and handles the data via a callback not a return value
So:
$.getJSON("test.json", handleData);
function handleData(data) {
console.log(data);
}
You also have a syntax error in your JSON data. Use http://jsonlint.com/ to pinpoint it.
Related
My original project had only one level of JSON data but it has grown and I need a second nested layer.
From what I researched it seemed that I could simply take the original object.name and append it with the new member level I needed to create like object.members.name. However this spits back an error undefined.
Clearly something is wrong or missing and I've been scratching my head for a while now.
I checked my JSON formatting a bunch of times and ran it through a validator (which checked out OK), no errors show up in the console and any search I make seems to bring up a much more complicated scenario then mine. I can't seem to narrow down what the problem is.
Any help or direction is much appreciated!
Here are the code blocks:
Non working multi level
Working single level
Non working multi level JSON data version
var obj =
{
"results": [
{
"members": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
}
]
}
]
};
$(obj.results).each(function(k,object){
var output = $("div.output");
output.append(object.members.name + " ");
output.append(object.members.phone + "<br />");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"></div>
Working single level JSON data version
var obj = {
"results": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
}
]
};
$(obj.results).each(function(k,object){
var output = $("div.output");
output.append(object.name + " ");
output.append(object.phone + "<br />");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"></div>
Nest your each statements?
var obj = {
"results": [{
"members": [{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
}
]
}]
};
$(obj.results).each(function(k, result) {
var output = $("div.output");
$(result.members).each(function(index, member) {
output.append(member.name + " ");
output.append(member.phone + "<br />");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output">
</div>
Of course, I'd avoid using names like 'object' or 'obj' -- use result and member instead. Far more mnemonic. You'll know exactly what it refers to.
We're having a lot of trouble doing a partial update in DynamoDB.
Trying to use best practices in NoSQL by using aggregates instead of entities so our data looks a bit like this:
[
{
"userLogin": {
"ipAddress": "123.222.121.1234",
"lastLogin": "2017-10-16T17:38:59.818Z",
"userAgent": "bob",
"geoLocation": "lat-121 long-312"
},
"addresses": {
"billingAddress": {
"streetName": "york street",
"province": "ontario",
"city": "toronto",
"streetNumber": "18",
"postalCode": "m5a2v7"
},
"businessAddress": {
"streetName": "york street",
"province": "ontario",
"city": "toronto",
"streetNumber": "18",
"postalCode": "m5a2v7"
},
"mailingAddress": {
"streetName": "york street",
"province": "ontario",
"city": "toronto",
"streetNumber": "18",
"postalCode": "m5a2v7"
},
},
"paymentTransaction": {
"orderId": 5,
"amount": 75,
"transactionTimestamp": "2017-10-16T17:38:59.818Z"
},
"userId": "00uc4sxyi7gfQoFum0h7",
"phoneNumbers": {
"workNumber": "647-123-1234",
"homeNumber": "647-321-4321"
},
"userProfile": {
"role": "admin",
"verifiedTimeStamp": "2017-10-16T17:38:59.818Z",
"termsConditionTimeStamp": "2017-10-16T17:38:59.818Z",
"verified": "TRUE",
"createdTimeStamp": "2017-10-16T17:38:59.818Z",
"termsConditionVersion": "1.0",
"email": "kyle.truong#test.io"
}
}
]
All we want to do is make a request with a body like this:
PUT /api/user-profiles/00uc4sxyi7gfQoFum0h7
body: {
"userLogin": { "lastLogin": "2017-12-16T17:38:59.818Z" }
}
and have it update the one attribute in the User table.
The updateItem API seems to require defining the attributes you want to update before updating them, but we want it be more flexible and dynamic based on the body of the request.
This thread seems to say it's not possible:
How to update multiple items in a DynamoDB table at once
If so, what's the best way to go about updating just a partial attribute object within an item in DynamoDB?
In dynamoDB if your userLogin is a map type then you can update the value of lastLoginkey. In Java below code may help. Here column name would be userLogin and newKey would be lastLogin. Full code snippet can be found here
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(primaryKey,primaryKeyValue).withReturnValues(ReturnValue.ALL_NEW).
withUpdateExpression("set #columnName." + newKey + " = :columnValue").
withNameMap(new NameMap().with("#columnName", updateColumn)).
withValueMap(new ValueMap().with(":columnValue", newValue)).withConditionExpression("attribute_exists("+ updateColumn +")");
table.updateItem(updateItemSpec);
I have an array in the below format which I need to filter based on the key and value. I am planning to use Underscore.js for this. I tried using the following code but it searches for all the fields value but I need to search based on the key and value and not in all the keys. How to use Underscore for this?
Please let me know.
var sortedArray = _.sortBy(_.filter(arr, function (obj) {
return _.values(obj).some(function (el) {
return (typeof el ==="string" && el.match(new RegExp(searchStr, "i")));
});
}), function (obj){
return obj[colName];
});
}
{
"recordsTotal": 5,
"recordsFiltered": 5,
"aaData": [
{
"firstname": "Pradeep",
"lastname": "Kumar",
"city": "Bangalore",
"country": "India"
},
{
"firstname": "John",
"lastname": "Wells",
"city": "Calcutta",
"country": "India"
},
{
"firstname": "Praveen",
"lastname": "Garg",
"city": "columbo",
"country": "Srilanka"
},
{
"firstname": "Joe",
"lastname": "Wells",
"city": "Luton",
"country": "UK"
},
{
"firstname": "Rita",
"lastname": "Wahlin",
"city": "houston",
"country": "USA"
}
]
}
Sorry if I was not able to post the question properly. I found a solution and the is using the below code.
var searchColData=function(arr, searchStr, colName){
var sortedArray = _.filter(arr, function (obj) {
return (_.property(colName)(obj).toString().match(new RegExp(searchStr, "i")));
});
return sortedArray;
}
Hope this helps someone.
How could i parse this type of json data, getting in "results" to fetch single values like zipcode, state etc
{
"row": [
{
"id": "5",
"name": "test",
"email": "test#test.com",
"street": "mystreet",
"city": "mycity",
"state": "mystate",
"zipcode": "123456",
"myimage": "image.gif"}
]
}
first, you need to parse that string with JSON.parse
var myJson = JSON.parse(the_raw_data_string);
it ends up into an object like this:
var myJson = {
"row": [
{
"id": "5",
"name": "test",
"email": "test#test.com",
"street": "mystreet",
"city": "mycity",
"state": "mystate",
"zipcode": "123456",
"myimage": "image.gif"}
]
}
accessing the items:
myJson.row[0].id
myJson.row[0].name
myJson.row[0].street
//and so on...
you can take the json result to a var like follows
var json = {
"row": [
{
"id": "5",
"name": "test",
"email": "test#test.com",
"street": "mystreet",
"city": "mycity",
"state": "mystate",
"zipcode": "123456",
"myimage": "image.gif"}
]
}
then get the result to another
var result = json.row;
then you can iterate through the result
for (var i = 0; i < result.length; i++) {
var object = result[i];
for (property in object) {
var value = object[property];
alert(property + "=" + value); // This alerts "id=5", etc..
}
}
hope this will help you
Again here jQuery is your good friend
I have posted a sample using jsfiddle with multiple records in your data row
$(document).ready(function () {
var result = {
"row": [
{
"id": "5",
"name": "test",
"email": "test#test.com",
"street": "mystreet",
"city": "mycity",
"state": "mystate",
"zipcode": "123456",
"myimage": "image.gif"
},
{
"id": "10",
"name": "test2",
"email": "test2#test.com",
"street": "mystreet2",
"city": "mycity2",
"state": "mystate2",
"zipcode": "7891011",
"myimage": "image.gif"
}
]
};
var oE = $("#output");
$.each(result.row, function(index, value) {
//- extract target value like zipCode
oE.append($("<li></li>").text(value.zipcode));
});
});
Hope this helps.
If the json data is raw then use json.parse.
After that to loop the multi dimensional json data.
data = {"employees":[
{ "firstName":"Anushka", "lastName":"shetty" },
{ "firstName":"Shreya", "lastName":"Saran" },
{ "firstName":"Kajal", "lastName":"Agarwal" }
]};
for (var key in data.employees) {
alert(data.employees[key].firstName) //alert Anushka, Shreya, Kajal
}
You can use JQuery each function:
$.each(myData.row, function(index,item) {
// here you can extract the data
alert (item.zipcode);
});
Use JSON.parse(jsonstring). Then iterate over the objects/arrays.
I have a nested json. I want to post it as a form input value.
But, seems like jquery puts "Object object" string into the value.
It seems easier to pass around the string and convert into the native form I need, than dealing with json as I don't need to change anything once it is generated.
What is the simplest way to convert a json
var json = {
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
],
"newSubscription": false,
"companyName": null
};
into its string form?
var json = '{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
],
"newSubscription": false,
"companyName": null
}'
Following doesn't do what I need:
Json.stringify()
jQuery doesn't have a method for JSON stringifying native objects. You will need json2.js which will provide the JSON.stringify() method to browsers that don't already support it.