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);
Related
Working on JavaScript app and need help in creating a new object from response received from ajax call.
The output received is array of objects, sample format below:
{
"items": [
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to swim",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}
]
}
However, my component expects JS Object in the following format:
{
id: "e1",
title: "Express",
start: "Jan 13, 2010",
description: "Jan 13, 2010"
}
Is following approach correct, please suggest better approach if any
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}
}
};
var gcalEvents = {};
var jsonObj = {
"id": "e1",
"title": "Oracle Application Express",
"start": "Jan 13, 2010",
"description": "Jan 13, 2010"
};
console.log(content.items.length);
for (var index = 0; index < content.items.length; index++) {
var obj = content.items;
console.log(obj);
jsonObj.id = obj[index]["id"];
jsonObj.title = obj[index].summary;
jsonObj.start = obj[index].start.dateTime;
jsonObj.description = "";
console.log(jsonObj);
gcalEvents[index] = jsonObj;
}
console.log(gcalEvents);
You could take a more functional approach with the following:
var parsed = content.items.map(function (item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: item.start.dateTime
}
})
This uses the map method that is attributed with arrays to loop over each item of the array and return a new array of parsed objects.
Take a look at this fuller example.
I have another way to convert this content.
Using Underscore.js to make the code more readable.
Here is the example:
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}, {
"id": "nj4h567r617n4vd4kq98qfjrek",
"summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": {
"dateTime": "2017-03-07T11:30:00+05:30"
}
}]
};
var result = _.map(content.items, function(item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: ""
};
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
The result as following:
[
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"title": "Learn to code",
"start": "2017-03-04T19:00:00+05:30",
"description": ""
},
{
"id": "nj4h567r617n4vd4kq98qfjrek",
"title": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": "2017-03-07T11:30:00+05:30",
"description": ""
}
]
At the core, you are trying to 'map' from one set of data to another. Javascript's mapping function of array should be sufficient. Eg.
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}]
};
var results = content.items.map(function (item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: ""
};
});
console.log(results);
var jsonObj=[];
for (var index = 0; index < content.items.length; index++) {
var obj = {};
console.log(obj);
obj["id"]=content.items[index].id;
obj["title"]=content.items[index].summary;
obj["start"]=content.items[index].start.dateTime;
obj["description"]="";
jsonObj.push(obj);
console.log(jsonObj);
//gcalEvents[index] = jsonObj;
}
This will give you jsonObj as your desired json object.
Hope this helps :)
Here's the fixed code:
One error was when you've listed the content items, a "]" was missing at the end.
The second one was that you were trying to assign a values to an undefined object, you first need to define the object eg: jsonObj = {}; and then do the assigning of values.
I've preferred to do the object define and assigning of the values in one go.
In order to have the output as an array, you just have to define the colection as an array and not am object eg: var gcalEvents = []
var content = {
"items": [
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
},
{
"id": "nj4h567r617n4vd4kq98qfjrek",
"summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": {
"dateTime": "2017-03-07T11:30:00+05:30"
}
}
]
};
var gcalEvents = [];
var jsonObj = {
"id": "e1",
"title": "Oracle Application Express",
"start": "Jan 13, 2010",
"description": "Jan 13, 2010"
};
//console.log(content.items.length);
for(var index=0; index < content.items.length; index++){
var obj = content.items[index];
//console.log(obj);
jsonObj = {
'id': obj["id"],
'title': obj.summary,
'start': obj.start.dateTime,
'description': ""
}
//console.log(jsonObj);
gcalEvents[index] = jsonObj;
}
console.log(gcalEvents);
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>
The url has following json data:
[{ "topic": "cricket",
"value": "Player [ playerid=123, category=b, high=150, total=2300]",
"place": "xyz"},
{ "topic": "cricket",
"value": "Player [ playerid=456, category=c, high=60, total=300]",
"place": "abc"},
{ "topic": "cricket",
"value": "Player [ playerid=789, category=a, high=178, total=5300]",
"place": "bnm"}]
I tried online to check whether this is valid json or not through following link: http://jsonformatter.curiousconcept.com/ it says valid. if it is, how do I access each playerid ?
It is valid JSON, but the data about the player is embedded in a random string. You can do one of two things:
Update the service to send back a different, valid JS value, for example:
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
}
Parse the data in the value key yourself:
// Simple regex, not really "parsing"
var playerIdRE = /playerid=(\d+)/i;
var result = playerIdRE.exec(yourData[0].value);
// result[0] is the full match, while result[1] is the ID.
// Or the more complicated version that does full parsing
var format = /\s*(.*?)\s*\[\s*([^\]]+)\s*\]\s*/gi,
keyValuePair = /(\w+)=([^,\]]*),?\s*/gi
function parseComplexDataType(input) {
var result = format.exec(input),
typeName = result[1],
keyValues = result[2],
returnValue = {};
if (!typeName) return returnValue;
returnValue.typeName = typeName;
input.replace(keyValuePair, function(_, key, value) {
returnValue[key] = value;
});
return returnValue;
}
// Usage:
> parseComplexDataType("Player [ playerid=123, category=b, high=150, total=2300]")
Object {typeName: "Player", playerid: "123", category: "b", high: "150", total: "2300"}
For your purposes, it is not valid. Once the JSON is corrected, you simply need to loop through the array and read each value.
var jArray = [{
"topic": "cricket",
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
},
"place": "xyz"
}, {
...
}]
To access the JSON data ...
for (var i=0,len=jArray.length; i<len; i++) {
console.log(jArray[i].topic, jArray[i].value.type);
}
Yes, it is. I check it via: http://jsonlint.com/
Extracting "playerid":
Initialise the string to JSONArray.
Iterate over each element in the above array.
Now, from each element extract "value".
Finally, from this string you can get "playerid" by using string methods (see the code below).
Below is the code in Java:
ArrayList<String> player_ids = new ArrayList<String>();
String s = "YOUR STRING";
JSONArray ja = new JSONArray(s);
for(int i =0; i<ja.length(); i++)
{
String value = ja.getJSONObject(i).getString("value");
int start = value.indexOf("=");
int end = value.indexOf(",");
String player_id = value.substring(start+1, end);
player_ids.add(player_id);
}
Hope it helps!!
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>
This is the JSON output that I currently have:
[{"pk": 1, "model": "system.employees",
"fields": {"chi_name": "N/A", "eng_name": "Eli"}}]
I want the output to be
[{"label": "Eli", "value": "1"}]
how can I take the values of pk and eng_name from the JSON data and output it like above?
You can use jQuery.map:
var data = [{"pk": 1, "model": "system.employees",
"fields": {"chi_name": "N/A", "eng_name": "Eli"}}];
var new = $.map(data, function(index, item) {
return { label: item.fields.eng_name, value: item.pk };
});
var result = [{"pk": 1, "model": "system.employees", "fields": {"chi_name": "N/A", "eng_name": "Eli"}}]
var output = [{ "label" : result[0].fields.eng_name, "value": result[0].pk}]
//assuming your source obj is called 'source'
var num = source[0].pk;
var eng_name = source[0].fields.eng_name;
...then you can do whatever with them, like
var output = [];
output.push({"label":eng_name, "value":num});
Good luck!
Try -
var h = JSON.parse('[{"pk": 1, "model": "system.employees", "fields": {"chi_name": "N/A", "eng_name": "Eli"}}]');
var a = [];
a.push({"label": h[0].fields.eng_name, "value": h[0].pk+''})
alert(JSON.stringify(a))
NB You'll need to import this code - https://github.com/douglascrockford/JSON-js/blob/master/json2.js if your browser doesn't support JSON.parse and JSON.stringify
Demo - http://jsfiddle.net/ipr101/uwZVW/