How to parse The following JSON in Javascript? - javascript

I am making a web app for nokia S40 platform . I am calling a web service using Javascript that returns the Following JSON
{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http:\/\/bit.ly\/msapps", "long_url": "http:\/\/www.microsoft.com\/web\/gallery\/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } }
I want to obtain the "short_url" and "long_url " values
I am using eval as var obj = eval ("(" + xmlhttp.responseText + ")");
where xmlhttp.responseText conatains the JSON response.
Please help

tried this and worked
var s = '{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http://bit.ly/msapps", "long_url": "http://www.microsoft.com/web/gallery/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } } '
var d = JSON.parse(s);
console.log(d.data.expand[0].short_url);
console.log(d.data.expand[0].long_url);

This expression
JSON.parse('{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http:\/\/bit.ly\/msapps", "long_url": "http:\/\/www.microsoft.com\/web\/gallery\/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } }').data.expand[0].short_url
returns "http://bit.ly/msapps"

How about this
var json = "{}" // Your JSON string
json = new Function('return ' + json)();
console.log(json.data.expand[0].short_url, json.data.expand[0].long_url);

Related

How to create a json object from another json object using JavaScript?

I am really junior with JavaScript and json, so I have this JSON input, and I need to get all that information in the "properties" object to create a new JSON object with just that information.
I'm using a base code like this one, but this is just returning {}.
exports.step = function(input, fileInput) {
var alert = {
'Properties': input.alert.properties
}
return JSON.stringify(alert, undefined, 1);
};
Original JSON:
"value": {
"id": "12345",
"entity": {
"_integrationDefinitionId": "7a6764",
"_integrationName": "Apple Main",
"_beginOn": "2021-09-01T02:20:06.189Z",
"displayName": "apple-onev",
"_accountIdPartitioned": "12345|12",
"_class": [
"Deployment",
"Group"
],
"_version": 3,
"_integrationClass": [
"CiSSP",
"Infrastructure"
],
"_accountId": "123456",
"_id": "1e234567",
"_key": "arn:aws:autoscaling:us-west-2:83712398:autoScalingGroup:asd1238-20c8-41aa-bcec-12340912341:autoScalingGroupName/awseb-e-juancito-stack-AWSEBAutoScalingGroup-123456",
"_type": [
"aws_autoscaling_group"
],
"_deleted": false,
"_rawDataHashes": "1233456==",
"_integrationInstanceId": "54321",
"_integrationType": "aws",
"_source": "integration",
"_createdOn": "2021-07-19T23:19:19.758Z"
},
"properties": {
"webLink": "https://google.com",
"arn": "name",
"region": "us-west-2",
"name": "JonnyAndTheVibes",
"launchConfigurationName": "OtherName",
"minSize": 1,
"maxSize": 4,
"desiredCapacity": 1,
"defaultCooldown": 360,
"availabilityZones": "us-west-2a",
"LoadBalancerNames": "MoreInfo",
"healthCheckType": "EC2",
"healthCheckGracePeriod": 0,
"instanceIds": "InstanceName",
"subnetIds": "subnet",
"terminationPolicies": "Default",
"newInstancesProtectedFromScaleIn": false,
"serviceLinkedRoleARN": "aMoreInfo",
"tag.Name": "atag",
"tag.application": "othertag",
"tag.aws:cloudformation:logical-id": "moretagsp",
"tag.aws:cloudformation:stack-id": "taggigante",
"tag.aws:cloudformation:stack-name": "ydaleconlostags",
"tag.elasticbeanstalk:environment-id": "seguimosmetiendoletags",
"tag.elasticbeanstalk:environment-name": "tag",
"tag.env": "tag",
"tag.team": "tag",
"accountId": "tag",
"tag.AccountName": "tag",
"tag.Production": true,
"#tag.Production": "​"
}
}
I'm sure that it will be a simple solution.
You appear to be trying to grab properties from the wrong object. It should be value not alert.
const json = '{"value":{"id":"12345","entity":{"_integrationDefinitionId":"7a6764","_integrationName":"Apple Main","_beginOn":"2021-09-01T02:20:06.189Z","displayName":"apple-onev","_accountIdPartitioned":"12345|12","_class":["Deployment","Group"],"_version":3,"_integrationClass":["CiSSP","Infrastructure"],"_accountId":"123456","_id":"1e234567","_key":"arn:aws:autoscaling:us-west-2:83712398:autoScalingGroup:asd1238-20c8-41aa-bcec-12340912341:autoScalingGroupName/awseb-e-juancito-stack-AWSEBAutoScalingGroup-123456","_type":["aws_autoscaling_group"],"_deleted":false,"_rawDataHashes":"1233456==","_integrationInstanceId":"54321","_integrationType":"aws","_source":"integration","_createdOn":"2021-07-19T23:19:19.758Z"},"properties":{"webLink":"https://google.com","arn":"name","region":"us-west-2","name":"JonnyAndTheVibes","launchConfigurationName":"OtherName","minSize":1,"maxSize":4,"desiredCapacity":1,"defaultCooldown":360,"availabilityZones":"us-west-2a","LoadBalancerNames":"MoreInfo","healthCheckType":"EC2","healthCheckGracePeriod":0,"instanceIds":"InstanceName","subnetIds":"subnet","terminationPolicies":"Default","newInstancesProtectedFromScaleIn":false,"serviceLinkedRoleARN":"aMoreInfo","tag.Name":"atag","tag.application":"othertag","tag.aws:cloudformation:logical-id":"moretagsp","tag.aws:cloudformation:stack-id":"taggigante","tag.aws:cloudformation:stack-name":"ydaleconlostags","tag.elasticbeanstalk:environment-id":"seguimosmetiendoletags","tag.elasticbeanstalk:environment-name":"tag","tag.env":"tag","tag.team":"tag","accountId":"tag","tag.AccountName":"tag","tag.Production":true,"#tag.Production":"​"}}}';
function getAlert(dsta) {
// Destructure the properties object from the
// data's value property
const { properties } = data.value;
// Create a new object with it
const alert = { properties };
// Return the string
return JSON.stringify(alert, null, 2);
};
// Parse the JSON
const data = JSON.parse(json);
// Call the function with the parsed data
const alert = getAlert(data);
console.log(alert);
Additional information
Destructuring assignment
use this function :
function assignJsons(...jsons) {
const convertToObject = jsons.map(json => {
return JSON.parse(json)
});
return JSON.stringify(Object.assign(...convertToObject))
}
//test
console.log(assignJsons(`{"name" : "alex", "family" : "mask"}`, `{"family" : "rejest"}`))
if you want a completely new object
var newJsonObject = JSON.parse('{ "properties":'
+ JSON.stringify (origJson.value.properties) + "}");
or
var newJsonObject={"properties":Object.assign ({}, origJson.value.properties)};

How to get the attribute url? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I am trying to fetch the attributes from the JSON.How to get the attribute url from the below JSON body?
I am receiving undefined in console
Here is my cloud function from
// shipmentai map tracking
exports.shipmentmaptracking = functions.https.onRequest((req, res) => {
var request = require("request");
var trackid = req.body.Tracking;
let d = {
"tracking_pages": [
{
"branded_tracking_theme_guid": "440bed90-617b-43ba-bd0e-31512ac66e23",
"tracking_number": "9400111699000367101815",
"carrier_code": "stamps_com",
"service_code": "usps_priority_mail",
}
]
};
var options = {
method: 'POST',
url: 'https://api.shipengine.com/v-beta/tracking_page',
headers: {
'Content-Type': 'application/json',
'api-key': 'Wyo4gpVIXfElQSDgF9p/L9aQ9kX3Um60X8hRSo8VAes'
},
body: JSON.stringify(d),
};
console.log('Sending a ' + options.method + ' request to ' + options.url);
request(options, function (error, response, body) {
console.log('Successfully received a response from ShipEngine')
if (error) {
console.log('An error was returned: ' + error.message);
res.status(500).send(error.message);
}
else if (response.statusCode >= 400) {
console.log('An error was returned: ' + response.statusCode + ' ' + response.statusMessage);
console.log(body);
res.status(response.statusCode).send(body);
}
else {
console.log('A successful response was returned');
console.log(body);
console.log(d.tracking_pages[0].url);
//res.status(200).send({'URL':shippp.tracking_pages[0].url});
console.log('statusCode:', response && response.statusCode);
}
});
});
Here is my Json output
How to fetch the attribute URL from the JSON below
{
"tracking_pages": [
{
"carrier_code": "stamps_com",
"tracking_number": "9400111699000367101815",
"branded_tracking_theme_guid": "440bed90-617b-43ba-bd0e-31512ac66e23",
"token": "l1XKcsYaEECc903KqBvtaA",
"url": "https://track.shipengine.com/se/v1/g/l1XKcsYaEECc903KqBvtaA",
"service_code": "usps_priority_mail"
}
],
"page": 0,
"pages": 0,
"total": 0
}
Thanks in advance
Simply get it from the data - note that I have given the entire object a name ("data") and that tracking_pages is an array - so you have to use the index number to get at it (assuming that there will be morethan one - otherwise there is no need to use an array) - and then its just the url property within that.
data.tracking_pages[0].url;
Obviously you will need a bit more sophistication in the selction - I's assuming that the actual data is more complex. And you can use JSON.parse() to convert the json o a regualr object.
But its just as simple as traversing the parents in the object and getting the selector correct.
let data = {
"tracking_pages": [
{
"carrier_code": "stamps_com",
"tracking_number": "9400111699000367101815",
"branded_tracking_theme_guid": "440bed90-617b-43ba-bd0e-31512ac66e23",
"token": "FmUfsOmjdEuioBuen1lMVA",
"url": "https://track.shipengine.com/se/v1/g/FmUfsOmjdEuioBuen1lMVA",
"service_code": "usps_priority_mail"
}
],
"page": 0,
"pages": 0,
"total": 0
}
let trackingUrl = data.tracking_pages[0].url;
console.log(trackingUrl) // gives https://track.shipengine.com/se/v1/g/FmUfsOmjdEuioBuen1lMVA
You can use . notation to access the url property in the object
var a={
"tracking_pages": [
{
"carrier_code": "stamps_com",
"tracking_number": "9400111699000367101815",
"branded_tracking_theme_guid": "440bed90-617b-43ba-bd0e-31512ac66e23",
"token": "FmUfsOmjdEuioBuen1lMVA",
"url": "https://track.shipengine.com/se/v1/g/FmUfsOmjdEuioBuen1lMVA",
"service_code": "usps_priority_mail"
}
],
"page": 0,
"pages": 0,
"total": 0
};
console.log(a.tracking_pages[0].url)
The expected output is not clear. If tracking_pages contain multiple url then you can use map to return an array of urls
let da = {
"tracking_pages": [{
"carrier_code": "stamps_com",
"tracking_number": "9400111699000367101815",
"branded_tracking_theme_guid": "440bed90-617b-43ba-bd0e-31512ac66e23",
"token": "FmUfsOmjdEuioBuen1lMVA",
"url": "https://track.shipengine.com/se/v1/g/FmUfsOmjdEuioBuen1lMVA",
"service_code": "usps_priority_mail"
}],
"page": 0,
"pages": 0,
"total": 0
}
let urlAr = da.tracking_pages.map(item => item.url);
console.log(urlAr)

Create a nested JSON Object with Javascript

I´d like to create a JSON-Object for a Google API-Request. Only content is needed to change. My solution gives me an invalid JSON-Format and is more a hack. Is there an easier way to do this? Thank your for your hints.
The necessary format look like this:
{
"requests": [
{
"image": {
"content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
]
}
JS
var cvs = cvs.substring('data:image/png;base64,'.length);
var json1 = '{"requests":[{ "image":{ "content":"'
var json2 = '"}, "features": [{"type":"DOCUMENT_TEXT_DETECTION"}] } ]}'
var entireJson = json1 + cvs + json2;
var ocrImage = JSON.stringify(entireJson);
What you have done in your example is initializing a Javascript Object.
JSON.parse(object_string); is not necessary. You may initialize it directly:
var ocrImage = {
"requests": [
{
"image": {
"content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
]
}
console.log(ocrImage)

Formatting JSON for email body

I've JSON in the following format that I'm trying to insert into outlook/email client's body using
location.href = "mailto:" + "email#domain.com" + "?subject=" + "Notes" + "&body=" + JSON.stringify(data, null, 4);
Giving 4 spaces JSON.stringify(data, null, 4)
[
{
"page": "article_0_page_0",
"note": "Note 1"
},
{
"page": "article_0_page_1",
"note": "Note 2"
}
]
I want to output as
<b>article_0_page_0</b>\n\r
Note 1
<b>article_0_page_1</b>\n\r
Note 2
Any regular expression solution please.
Edit: My attempt
var str = "";
for(var i=0; i<data.length; i++) {
str += "<strong>" + data[i].page + "</strong><br>" + data[i].note + "<br><br>";
}
I think the above answer is ok if you have a flat structure.
If you want a more holistic approach for email specifically, I have found this to work really well.
const data = {...}
JSON.stringify( data, null, ' ' ).split( '\n' ).join( '<br>' );
This will convert something like this
const json = {
"status": "ok",
"config": {
"gotIt": "yes",
"transform": [
null
]
}
}
Into something like this
{<br>&nbsp"status": "ok",<br>&nbsp"config": {<br>&nbsp&nbsp"gotIt": "yes",<br>&nbsp&nbsp"transform": [<br>&nbsp&nbsp&nbspnull<br>&nbsp&nbsp]<br>&nbsp}<br>}
Email clients will render this as the following
{
"status": "ok",
"config": {
"gotIt": "yes",
"transform": [
null
]
}
}
This is done by using the additional parameters in JSON.stringify which I don't see used very often if you want to read more about these parameters here is the link for them.
Here ya go
var json = [
{
"page": "article_0_page_0",
"note": "Note 1"
},
{
"page": "article_0_page_1",
"note": "Note 2"
}
];
var out = "";
for (var key in json) {
if (json.hasOwnProperty(key)) {
out += "<b>"+json[key].page+"</b>\r\n"+json[key].note+"\r\n\r\n";
}
}
console.log(out);
Example Here: https://jsfiddle.net/q5r4gdcn/1/
This is what I used to convert basic JSON to "readable" for email:
let json = {
"key": "asdas",
"query": "",
"hints": {
"nested1": "blahblah"
}
}
let prettyJSON = JSON.stringify(json, null, ' ')
.split('\n')
.join('<br> ')
.split('<br> }').join('<br>}')
document.body.innerHTML += `<div>${prettyJSON}</div>`

How to read array inside JSON Object this is inside another array

I am newbie to JSON, I am parsing a JSON Object and i was struck at a point where i have to read the array Elements inside a Object, that is again in another array..
Here is MY JSON
{
"DefinitionSource": "test",
"RelatedTopics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/a5e4a93a.jpg"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Result": "",
"Icon": {
"URL": "xyz"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Topics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/10d02dbf.jpg"
},
"FirstURL": "https://duckduckgo.com/Snake_Indians",
"Text": "sample"
},
{
"Result": "sample",
"Icon": {
"URL": "https://duckduckgo.com/i/1b0e4eb5.jpg"
},
"FirstURL": "www.google.com",
"Text": "xyz."
}
]
}
]
}
Here I need to read URL ,FIRSTURL and Text from RelatedTopics array and Topics array..
Can anyone help me. Thanks in advance.
Something like this
function (json) {
json.RelatedTopics.forEach(function (element) {
var url = element.Icon ? element.Icon.URL : 'no defined';
var firstURL = element.FirstURL ? element.FirstURL : 'no defined';
var text = element.Text ? element.Text : 'no defined';
alert("URL: " + url + "\nFirstURL: " + firstURL + "\nText: " + text);
if (element.Topics)
{
element.Topics.forEach(function (topicElement) {
alert("Topics - \n" + "URL: " + topicElement.Icon.URL + "\nFirstURL: " + topicElement.FirstURL + "\nText: " + topicElement.Text);
});
}
});
};
Look fiddle example
Loop through json Array like,
for(var i=0; i< RelatedTopics.length;i++){
if($.isArray(RelatedTopics[i])){
for(var j=0; j< RelatedTopics[i].Topics.length;j++){
var topics=RelatedTopics[i].Topics[j];
var text = topics.Text;
var firsturl = topics.Firsturl;
var url = topics.Icon.url;
}
}
}
if you want push it an array variable

Categories

Resources