Convert JSON object to JSON array with additional elements - javascript

I have the following JSON object
{
"https://www.google.com": "200",
"https://www.facebook.com": "200",
"https://www.yahoo.com": "401",
"https://www.friendster.com": "404"
}
Is it possible to convert it to a JSON array with additional elements (url & status) in Javascript?
[
{
"url": "https://www.google.com",
"status": "200"
},
{
"url": "https://www.facebook.com",
"status": "200"
},
{
"url": "https://www.yahoo.com",
"status": "401"
},
{
"url": "https://www.friendster.com",
"status": "404"
}
]
Thank you for the tips.

Parse the string using JSON.parse, get all keys as an array and construct an array of objects with url and status properties
var json = '{\
"https://www.google.com": "200",\
"https://www.facebook.com": "200",\
"https://www.yahoo.com": "401",\
"https://www.friendster.com": "404"\
}';
var obj = JSON.parse(json);
var objWithUrlAndStatus = Object.keys(obj).map(function (key) {
return {
url: key,
status: obj[key]
}
});
console.log(objWithUrlAndStatus);

You can use jquery $.each
like this
var data = {
"https://www.google.com": "200",
"https://www.facebook.com": "200",
"https://www.yahoo.com": "401",
"https://www.friendster.com": "404"
};
var finalData=[];
$.each(data,function(index,val){
finalData.push({url:index,status:val});
});
console.log(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

I need remove unnecessary json objects form my result json file using javascript

I have result json file with 10000 of lines. inside the one array object there are some unnecessary json object i need remove. I have tried so many ways but it's didn't work for me. herewith the piece line of json file
[
{
"product_id": "easybridge",
"errors": []
},
{
"product_id": "learningstudio",
"errors": []
},
{
"product_id": "pearsontestprep",
"errors": []
},
{
"product_id": "productization",
"errors": []
},
{
"product_id": "equella",
"errors": [
{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
"schema": {
"$id": "#/properties/test_ids/items",
],
"properties": {
"trend": {
"$id": "#/properties/test_ids/items/properties/trend",
"examples": [
true
]
},
"display": {
"$id": "#/properties/test_ids/items/properties/display",
"type": "boolean",
"examples": [
true
]
},
"test_id": {
"$id": "#/properties/test_ids/items/properties/test_id",
"type": "string",
},
"test_name": {
"$id": "#/properties/test_ids/items/properties/test_name",
"type": "string",
},
"maintenance": {
"$id": "#/properties/test_ids/items/properties/maintenance",
"type": "boolean",
]
},
"instance": {
"trend": false,
"display": false,
"test_id": "8597ae3c-e2a9-45c7-b279-bde1710681be",
"test_name": "Equella Pearsonresearch Ping Test",
"nrAlertStatus": "enabled",
"test_locations": [
{
"alert_state": false,
"location_name": "AWS_US_WEST_2",
"location_label": "Portland, OR, USA",
"included_to_health": false
}
],
"included_to_health": false,
"critical_alert_threshold": 60
},
"name": "required",
"argument": "maintenance",
"stack": "instance.test_ids[1] requires property \"maintenance\""
{
"product_id": "easybridge",
"errors": []
},
I just need only
{
"product_id": "equella",
"errors": [
{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
}
},
if the errors json array is not empty. i don't need even this json how can i remove "schema" json object and other unnecessary json object and arrays specially "schema" json object using java script or java. please help
Loop through the array, look at each object, and create a new array by copying over the data you need.
For instance, I'm taking it you don't care about an object if its array of errors is empty, and that you don't care about the schema ever:
let newJSON = [];
//Assume the json variable is the parsed JSON file you posted.
for (let element of json) {
//Must have at least one error
if (element.errors.length > 0) {
//Create a new object
let newObj = {
"product_id" : element.product_id,
"errors" : []
};
//Add each errror
for (let error of element.errors) {
//Only copy across what we need
newObj.errors.push({
"property" : error.property,
"message" : error.message
});
}
//Add object to our new array of JSON
newJSON.push(newObj);
}
}
//newJSON is your processed JSON output
The easiest solution can be:
const records = [{
"product_id": "learningstudio",
"errors": []
},
{
"product_id": "pearsontestprep",
"errors": []
},
{
"product_id": "equella",
"errors": [{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
"schema": {
"$id": "#/properties/test_ids/items",
}
}]
}];
const filteredRecords = records.map((record) => {
record.errors = record.errors.map((error) => {
return {property: error. property, message: error.message};
});
return record;
});
console.log(filteredRecords);
You can use map and destructuring assignment to capture only desired properties
let json = [{"product_id": "equella", "errors": [{"property": "instance.test_ids[1]","message": "requires property \"maintenance\"",'xyz': 'not needed','useless': 'not needed',},{'xyz': 'not needed',}]},]
let op = json.map(({product_id,errors}) =>{
let { property, message } = errors[0]
return { product_id, errors: {property,message}}
})
console.log(op)

Delete a Json line using javascript

My API retrieve a Json like this :
{
"name": "API",
"count": 30,
"newdata": true,
"lastrunstatus": "success",
"thisversionstatus": "success",
"thisversionrun": "Mon Sep 07 2015 20:31:07 GMT+0000 (UTC)",
"results": {
"collection1": [
{
"name": "Item1",
"power": "210",
"name": {
"href": "http://picture.item42.com/item42.html",
"text": "Hammer of god"
},
"desc": "Iron Hammer",
"index": 1,
"url": "http://picture.item42.com/"
},
{
"name": "Item2",
"power": "230",
"name": {
"href": "http://picture.item42.com/item43.html",
"text": "Sword of god"
},
"desc": "Iron sword",
"index": 1,
"url": "http://picture.item43.com/"
}
]
}
I would like to delete the line "url" for each one, and delete le "href" property for the name to have "name" : "Hammer of god";
I try this and many other way (first step to delete the url):
data contains the Json that I copied upper
function transform(data) {
var yourArray = data.results.collection1;
var p = 0;
var i = 0;
var destArr=[];
var srcArr=yourArray;
for(i in srcArr){
if(srcArr[i].url)
destArr[p]=srcArr[i];
p++;
}
srcArr=destArr;
return srcArr;
}
Maybe its better to use data.results.collection1.filter ?
actually my code return the json without the header but still with the url row
Simply go through your json.result.collection1 and remove href on each name and url:
for(item in json.results.collection1) {
delete json.results.collection1[item].name.href
delete json.results.collection1[item].url;
}
Fiddle Example
Use the delete keyword to delete a property from the JSON.
var jsonObj = JSON.parse('your json string');
delete jsobObj.whateveryYourpropertyName;
var json = document.getElementById('json').value;
var obj = JSON.parse(json);
obj.results.collection1.forEach(function(entry) {
delete entry.url;
delete entry.name.href;
});
document.getElementById('result').value = JSON.stringify(obj);
JSFiddle
you should use the JSON delete method for what you want to achieve:
Where data is your json object:
data.results.collection1.forEach(function(el) {
delete el.url
delete el.name.href
});
You can simply use a second forEach loop in case you need to iterate through multiple collections.
Try the following:
jsonData.results.collection1.map(function(obj, index){
delete obj.url;
obj.name = obj.name.text;
return obj;
});
console.log(jsonData);

loop through a json object in ajax response [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 8 years ago.
I am new to json so i am getting a json reponse from my ajax call
now i am stuck with looping the json object
here is my json
{
"0": {
"image": "http://test.com/systems.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "Oct-Dec-2013"
},
"1": {
"image": "http://test.com/energy.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "July-Sept-2013"
},
"pages": 2
}
Can anyone help
You can use a for-in loop as follows:
var obj = {
"0": {
"image": "http://test.com/systems.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "Oct-Dec-2013"
},
"1": {
"image": "http://test.com/energy.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "July-Sept-2013"
},
"pages": 2
}
for(var prop in obj) {
var item = obj[prop];
console.log(item);
}
Be aware that you will get the items in your log because you will get the pages property in addition to the numeric properties.
Save your JSON response in a variable
var variable = {
"0" : {
"image" : "http://test.com/systems.jpg",
"anchor_tag_link" : "http://test.com/1",
"title" : "Oct-Dec-2013"
},
"1" : {
"image" : "http://test.com/energy.jpg",
"anchor_tag_link" : "http://test.com/1",
"title" : "July-Sept-2013"
},
"pages" : 2
};
Then loop it using jquery
$.each(variable, function(index, value) {
alert(value.image);
alert(value.anchor_tag_link);
});
you can do this.
var json = JSON.parse(data);// here data is your response
for (var key in json) {
alert(json[key].image);// other also in the same way.
}
Example 1 :
success: function(responseData) {
for (var key in responseData) {
alert(responseData[key]);
}
}
Example 2 :
<script>
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name); //mkyong
alert(json.address.streetAddress); //88 8nd Street
alert(json["address"].city); //New York
alert(json.phoneNumber[0].number); //111 111-1111
alert(json.phoneNumber[1].type); //fax
alert(json.phoneNumber.number); //undefined
</script>
Sample Code
Please try the following code. You only have to replace "yourJSONObject" by the JSON array.
$.each( yourJSONObject, function( keyImg, valImg ) {
image = valImg[0];
anchor_tag_link = valImg[1];
title = valImg[2];
});
Regards,
you can loop through this like looping through javascript object :
for(var arg in object) {
object.hasOwnProperty(arg) {
process(object[arg]);
}
}
JQuery:
var JSON = {
"0": {
"image": "http://test.com/systems.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "Oct-Dec-2013"
},
"1": {
"image": "http://test.com/energy.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "July-Sept-2013"
},
"pages": 2
};
if(JSON.pages >0)
{
for(var i=0; i<JSON.pages; i++)
{
$('table').append('<tr><td>'+JSON[i].title+'</td><td>'+JSON[i].image+'</td><td>'+JSON[i].anchor_tag_link+'</td></tr>');
}
}
HTML:
<table border="1"></table>

Retrieving value of JSON object with string variable

I have a json data
var data={"mainVariants": [
{
"header": "Measure"
},
{
"header": "Disposal"
},
{
"header": "Stairs"
},
{
"header": "Furniture"
}
],
"Measure": {}}
var val1=data.mainVariants[0].header;//returned as "Measure"
Now i want to retrieve data.val1.Pls help
Try this
var val1 = data.mainVariants[0].getString("header");
You can just do var obj = data[val1]

Categories

Resources