Displaying Dictionary in Javascript Object - javascript

I'm returning this response from my server:
callback({"City": "Miami", "State": "FL", "Street": "9th Street", "Name": "Big 12", "Zip": "65201", "Lat": -48.219999999999999, "Telephone": "5732168906", "Long": 32.0, "Events": "[{\"End Time\": \"2011-01-22 23:36:31\", \"Name\": \"Margaritas\", \"Start Time\": \"2011-01-22 15:36:31\"}, {\"End Time\": \"2011-01-22 19:36:39\", \"Name\": \"Dollar Bottles\", \"Start Time\": \"2011-01-22 15:36:39\"}, {\"End Time\": \"2011-01-23 23:36:31\", \"Name\": \"All You Can Drink\", \"Start Time\": \"2011-01-23 15:36:31\"}]"})
Here is where I'm attempting to parse the response and display it within my "tonight-list". With data.Events, I get the entire array of dictionaries displayed on screen.
function callback(data){
console.log(data);
$("#tonight-list").append("<li role='option' tabindex='0' class='ui-li ui-li-static ui-btn-up-c'>Starts:" +
data.Events +
"<li>");
However, I cannot figure out how to access each element (Start Time, End Time, Name, etc.). When I try data.Events[0], it gives me just the first character from data.Events.
How do I access each dictionary key in the array of Events? I just cannot figure out the syntax - it would be nice if I could see all the options on this object type. Thanks for the help in advance!

Make the Events in the JSON response a real array instead of a string, then you can use it like this:
var obj = JSON.parse(reponseText);
var event = obj.Events[0];
alert(event["End Time"]); // hurray
JSON response
callback({
"City": "Miami",
"State": "FL",
"Street": "9th Street",
"Name": "Big 12",
"Zip": "65201",
"Lat": -48.219999999999999,
"Telephone": "5732168906",
"Long": 32.0,
"Events": [{
"End Time": "2011-01-22 23:36:31",
"Name": "Margaritas",
"Start Time": "2011-01-22 15:36:31"
},
{
"End Time": "2011-01-22 19:36:39",
"Name": "Dollar Bottles",
"Start Time": "2011-01-22 15:36:39"
},
{
"End Time": "2011-01-23 23:36:31",
"Name": "All You Can Drink",
"Start Time": "2011-01-23 15:36:31"
}]
})​;

JSON dude! just return valid JSON from your server and use evalJSON. Then you can access each object via their corresponding keys.
edit:
basically do,
data.responseText.evalJSON();

Related

Javascript JSON.parse() not working on a valid JSON string

I have looked at all similar questions to mine but cannot find any obvious errors in my code or my JSON string.
The script sends a request to a web service, which returns a JSON formatted string. Somehow, html related to debugging is getting tacked onto the end of the JSON string, so I remove it with the string.slice method, to return only the content between the opening and closing square brackets. When I output the slice, everything is there. When I check the resultant slice for proper JSON formatting in jsonlint, it passes. But when I try to parse the string and create an alert of the parsed data, I get an error: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ) at XMLHttpRequest.request.onload
Here is the JSON string after slicing, taken directly from the jsonlint output:
[{
"user_id": "23",
"name": "Steven Marsden",
"email": "naturevet1#gmail.com",
"password": "$2y$10$FjDZAugd2Mj9tw.z8U1mWexLF0vkD7jnB5xusGyClDUXZwQC6u9iy",
"address": "2639 Valley Rdg Rd, Blairmore, AB T0K 0E0, Canada",
"lat": "49.617134",
"lng": "-114.388893",
"created_at": "2021-06-06 18:00:20",
"updated_at": "2021-06-06 18:00:20",
"services": [{
"u_s_id": "2",
"user_id": "23",
"mode": "seek",
"service": "pet sitting",
"details": "I have a dragon",
"img_file": null
}, {
"u_s_id": "3",
"user_id": "23",
"mode": "offer",
"service": "pet sitting",
"details": "I love dragons",
"img_file": null
}, {
"u_s_id": "7",
"user_id": "23",
"mode": "offer",
"service": "pet foster home",
"details": "Is it okay if my dragon eats your pet?",
"img_file": null
}],
"color": "red"
}]
Here is the javascript that requests the string and tries to parse it:
var url = 'http://localhost/helpinghands/public/index.php/services/getUsers';//Gets all users, complete with services offered and the appropriate marker color
var request = new XMLHttpRequest();
request.open('GET',url);
request.onload = function(){
if(request.status === 200){
var resp = request.responseText;
var slice = resp.slice(resp.indexOf('['),resp.indexOf(']')+1);//Cleaves any extraneous info from end of string to avoid JSON parse errors
var data = JSON.parse(slice);
//var userLat = Number(data[0].lat);
alert(data);
//var userLong = Number(data.lng);
//const loc = new point(userLat,userLong);//This is the location from the database for that user
//create marker object for loc by passing Marker constructor references to the loc and map objects, which are assigned to position and map variables, respectively
//const marker = new google.maps.Marker({map: map,position: loc, title: data.name});
}
};
Can anyone help me out?
Here is the output from the web service:
[{
"user_id": "23",
"name": "Steven Marsden",
"email": "naturevet1#gmail.com",
"password": "$2y$10$FjDZAugd2Mj9tw.z8U1mWexLF0vkD7jnB5xusGyClDUXZwQC6u9iy",
"address": "2639 Valley Rdg Rd, Blairmore, AB T0K 0E0, Canada",
"lat": "49.617134",
"lng": "-114.388893",
"created_at": "2021-06-06 18:00:20",
"updated_at": "2021-06-06 18:00:20",
"services": [{
"u_s_id": "2",
"user_id": "23",
"mode": "seek",
"service": "pet sitting",
"details": "I have a dragon",
"img_file": null
}, {
"u_s_id": "3",
"user_id": "23",
"mode": "offer",
"service": "pet sitting",
"details": "I love dragons",
"img_file": null
}, {
"u_s_id": "7",
"user_id": "23",
"mode": "offer",
"service": "pet foster home",
"details": "Is it okay if my dragon eats your pet?",
"img_file": null
}],
"color": "red"
}]
var slice = resp.slice(resp.indexOf('['),resp.indexOf(']')+1)
This function applied to your example JSON will cut off everything after the first ], which is the array nested under services, meaning that the first object in the json array will end up unclosed, as well as the json array that wraps the whole response.
You should fix the error in the server that returns HTML inside a JSON payload.
If that's not do-able, then you will need to detect the start of the HTML and cut there, though you are likely to keep experiencing more errors as a result of this faulty server endpoint

JavaScript access object

How can I get the "name" of the following JSON object?
"location": {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 15:03",
"localtime_epoch": 1587567780,
"utc_offset": "2.0"
}
["name"] returns the followin error
TypeError: Cannot read property 'name' of undefined
This could help you if not then let me know. If your json object is same as your_json_obj then you have to parse it first using JSON.parse(your_json_obj). If not then you simply use your_json_obj.location.name
const your_json_obj = "{
"location": {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 15:03",
"localtime_epoch": 1587567780,
"utc_offset": "2.0"
},
...}"
const name = JSON.parse(your_json_obj).location.name
console.log(name)
You can access its properties using location.name, location["name"], for example:
const location = {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 14:44",
"localtime_epoch": 1587566640,
"utc_offset": "2.0"
}
location.name;
location.["name"]
If you want to use it from the JSON object:
var y = '{"location": { "name": "Hilden", "country": "Germany", "region": "Nordrhein-Westfalen", "lat": "51.167", "lon": "6.933", "timezone_id": "Europe/Berlin", "localtime": "2020-04-22 15:03", "localtime_epoch": 1587567780, "utc_offset": "2.0" }}';
JSON.parse(y).location.name
So, in this case, you should use JSON.parse(jsonObject)) before access its properties. BUT NOTICE: "Make sure the text is written in JSON format, or else you will get a syntax error.", a "large text" inside {} - https://www.w3schools.com/js/js_json_parse.asp

How to Partially Update a DynamoDB Table?

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);

How to create markers to group AngularJS ng-repeat output by date (month)?

For a project I'm doing I'm outputting an array of data using ng-repeat from AngularJS and am trying to group the output by Month. There's no need to orderBy, since the data I get is already sorted, I just need to group it by Month.
The data I get from the API looks similar like this:
{"userinfo": [{
"date": "1305838800000",
"name": "john",
"lastname": "dough",
"city": "",
"province": "noord-holland",
"device": "macbook",
"phone": "iphone",
"provider": "t-mobile"
}, {
"date": "1305838800000",
"name": "john",
"lastname": "",
"city": "amsterdam",
"province": "noord-holland",
"device": "macbook",
"phone": "iphone",
"provider": "vodafone"
},{
"date": "1305838800000",
"name": "john",
"lastname": "",
"city": "amsterdam",
"province": "noord-holland",
"device": "macbook",
"phone": "iphone",
"provider": "t-mobile"
}, {
"date": "1305838800000",
"name": "john",
"lastname": "",
"city": "amsterdam",
"province": "noord-holland",
"device": "macbook",
"phone": "iphone",
"provider": "vodafone"
}]}
In here the field field would be the epoch date of the date I want to group by.
Any help on this grouping matter would be appreciated.
While this functionality will not land in AngularJS core:
https://github.com/angular/angular.js/issues/1649
You can either go with re-grouping an array into a map object on scope (Underscore.JS's groupBy is a nice example) or creating a new groupBy filter/use existing ones like:
https://github.com/samstokes/ng-group/
One plus for regrouping on scope - it will only happen once, while filters are re-evaluated on each digest.
There's no support for this kind of grouping in built-in angular directives. You'll need to create a copy of your model that you get from the server (a new collection), "manually" group the objects in the according months (by date) and then loop over that copy (in the view by using ng-repeat) instead of looping over the original model.

Convert json to a string using jquery

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.

Categories

Resources