Convert json to a string using jquery - javascript

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.

Related

Verify String is displaying within Nested JSON using Postman

I am working on Postman to verify some API calls, upon which I have gone through one of the end point, whose response is give below, and I need to make sure that within that JSON response:
[
{
"contact": {
"id": "k72yk2iwrf",
"firstName": "Francis",
"lastName": "Abell",
"title": "Translational Science Project Manager",
"company": "Sensei",
"email": "aa#aa.cpom",
"fax": {},
"businessAddress": {
"line1": "road",
"line2": "Street",
"line3": "Suite 710",
"city": "Boston",
"country": "US",
"postalCode": "02210",
"state": "MA"
},
"businessPhone": {
"number": "123-123-1234",
"ext": ""
},
"homeAddress": {},
"homePhone": {},
"mobilePhone": {}
},
"registration": {
"id": "104656",
"badgeId": "9208113975",
"eventId": "TESTLIBRA-10"
}
},
{
"contact": {
"id": "w4c4f2i7l4",
"firstName": "Francis",
"lastName": "Abell",
"title": "Translational Science Project Manager",
"company": "Sensei",
"email": "aa#aa.cpom",
"fax": {},
"businessAddress": {
"line1": "road",
"line2": "Street",
"line3": "Suite 710",
"city": "Boston",
"country": "US",
"postalCode": "02210",
"state": "MA"
},
"businessPhone": {
"number": "123-123-1234",
"ext": ""
},
"homeAddress": {},
"homePhone": {},
"mobilePhone": {}
},
"registration": {
"id": "104656",
"badgeId": "6803424516",
"eventId": "TESTLIBRA-10"
}
}
]
I can make sure that "eventId" is displaying and it is displaying "TESTLIBRA-10" value.
No matter, how long JSON response is, It can verify that this property , along with that value of that property are displaying.
I got my answer by myself, what I did was:
var jsonArrayData = pm.response.json();
pm.test('EventID property is displaying throughout JSON', function(){
jsonArrayData.each(function(eventID){
pm.expect(eventID.registration).to.have.property("eventId")
})
})
pm.test('Entered Libra EventID is entered', function(){
jsonArrayData.each(function(eventID){
pm.expect(eventID.registration.eventId).to.eql("TESTLIBRA-10")
})
})

Splitting a value in a json object and passing one part of that value to another key in the same object - javascript

I have a json file with shipping information and in the in the first address line I have an app number and the street address separated by "-". I need to split them and place the app number in the second address line.
Here is the example of the object:
{
"id": 34853873935,
"shipping_address": {
"address1": "944-3555 street name",
"address2": "",
"city": "City",
"company": null,
"country": "Country",
"country_code": "Code",
"first_name": "first",
"last_name": "last",
"latitude": 45.4966417,
"longitude": -73.5848221,
"name": "name",
"phone": null,
"province": "province",
"province_code": "code",
"zip": "zip"
}
You need to:
get the substring of address1 until the first space
split the result, using - as separator
get the first element of the result
prepend it at the start of address2
var obj = {
"id": 34853873935,
"shipping_address": {
"address1": "944-3555 street name",
"address2": "",
"city": "City",
"company": null,
"country": "Country",
"country_code": "Code",
"first_name": "first",
"last_name": "last",
"latitude": 45.4966417,
"longitude": -73.5848221,
"name": "name",
"phone": null,
"province": "province",
"province_code": "code",
"zip": "zip"
}
};
obj.shipping_address.address2 = obj.shipping_address.address1.substring(0, obj.shipping_address.address1.indexOf(" ")).split("-")[0] + (obj.shipping_address.address2 ? (" " + obj.shipping_address.address2) : "");
console.log(obj.shipping_address.address2);
You can use this code:
const shipping = {
"id": 34853873935,
"shipping_address": {
"address1": "944-3555 street name",
"address2": "",
"city": "City",
"company": null,
"country": "Country",
"country_code": "Code",
"first_name": "first",
"last_name": "last",
"latitude": 45.4966417,
"longitude": -73.5848221,
"name": "name",
"phone": null,
"province": "province",
"province_code": "code",
"zip": "zip"
}}
Here you can destructuring your object to extract an address1 variable or another's variables.
const { address1 } = shipping.shipping_address;
You can use a Regex where the first group captures a set of numeric characters at the beginning and before the "-" sign, and then extract a substring using the $1 assignment.
Then, in the second group, the capture of characters that meet the condition indicated in square brackets is omitted.
shipping.shipping_address.address2 = address1.replace(/^(\d{0,})(?:[-\d\w ]{0,})/gi, "$1");
output in console:
console.log(shipping)

Display multi level nested JSON data with JavaScript and jQuery

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.

Using ember-data with custom serializer

I have you could say a non standard json api. I'm trying to use ember-data with it so from my reading around I need to create a serializer. I tried to find article online explaining how to do this but haven't found anything useful. I tried looking through the ember guides but also found nothing. Here is an example of my api:
collection of data:
{
"data": [
{
"id": 14,
"name": "company name",
"slug": "company-name",
"detail": {
"data": {
"id": 10,
"address": "10000 sw 16th ct",
"city": "Hollywood",
"state": "Alabama"
}
},
"employees": {
"data": [
{
"id": 17,
"first_name": "Peter",
"last_name": "Griffin",
"email": "company-name#Griffin.co"
},
{
"id": 18,
"first_name": "Robert",
"last_name": "Gornitz",
"email": null
}
]
}
},
{
"id": 8,
"name": "company name",
"slug": "company-name",
"detail": {
"data": {
"id": 8,
"address": "1000 n university dr",
"city": "Fort Lauderdale",
"state": "West Virginia"
}
},
"employees": {
"data": [
{
"id": 15,
"first_name": "Peter",
"last_name": "Griffin"
},
{
"id": 16,
"first_name": "Peter",
"last_name": "Griffin"
}
]
}
}
]
}
Here is an item with its relationships:
{
"data": {
"id": 1,
"name": "company name",
"slug": "company-name",
"detail": {
"data": {
"id": 1,
"address": "1515 n university dr",
"city": "Miami",
"state": "Mississippi"
}
},
"employees": {
"data": [
{
"id": 1,
"first_name": "Peter",
"last_name": "Griffin",
"email": "peter#email.com"
},
{
"id": 2,
"first_name": "Peter",
"last_name": "Griffin",
"email": "peter#email.com"
}
]
}
}
}
Are there any good resources showing me how to do this? Or should I just not use ember-data?
Just some tips from my side using Ember Data. I believe that you either have to be able the adapt api or write a deserializer:
1. Root Key "data"
Ember expects the root key to be the name of the model (e.g. "company"). You can handle that easily by creating an application serializer and overwriting the extractArray and extractSingle method by grabbing the payload from the 'data' key instead of the model "typeKey".
2. Embedded Records
You can use the EmbeddedRecordsMixin. But for that you will have to skip the root key "data" in the embedded records and directly include them (e.g. "employees": [ { id: "2", ... }, ... ])
I'd have a look at the EmbeddedRecordsMixin for that:
http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html
http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize
Hope that helps a little.

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.

Categories

Resources