jquery parsing json - javascript

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/

Related

How do I create a new object from an existing object in Javascript?

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

Access nested members in JSON

I'm trying to access members in a json, however I am running into some trouble. Here is an example of one of the json objects, stored in var obj:
var fs = require('fs');
var obj = [
{
"_id": "52d7f816f96d7f6f31fbb680",
"regNum": "0361300035313000002",
"sd": "2013-01-01T00:00:00",
"pd": "2013-01-25T09:30:29Z",
"prd": "2012-12-18",
"p": 1395000000,
"pt": [
{
"name": name here",
"price": 1395000000,
"OKDP": {
"code": "5520109",
"name": "name here"
},
"sid": "25484812",
"sum": "1395000000",
"OKEI": {
"code": "796",
"name": "name two"
},
"quantity": "1"
}
],
"b": 0,
"c": 0,
"s": 0
}
];
I'm trying to access the sid and sum values, by doing the following:
var sid = [];
var sum = [];
obj.forEach(block => {
var sidOut = block.pt.sid;
var sumOut = block.pt.sum;
sid.push(sidOut);
sum.push(sumOut);
});
console.log(sid);
console.log(sum);
I tried the solution here, however, when I run these it gives me [ undefined ] errors.
Why am I unable to access this two values?
if you see your pt is an array of an object [{}] so you need to select which element you want to access so
var sidOut = block.pt[0].sid;
var sumOut = block.pt[0].sum;
should get you the right result

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

Is this valid json data?

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!!

Restructure JSON object

I have the following array:
var res = {
"status": "Success",
"data": [
{"assignedTo":"0", "createdDate":"23-07-2013", "count":"2"},
{"assignedTo":"182398", "createdDate":"01-08-2013", "count":"2"},
{"assignedTo":"182398", "createdDate":"23-07-2013", "count":"2"},
{"assignedTo":"182398", "createdDate":"24-07-2013", "count":"12"},
{"assignedTo":"182398", "createdDate":"22-07-2013", "count":"1"},
{"assignedTo":"182398", "createdDate":"30-07-2013", "count":"4"},
{"assignedTo":"182398", "createdDate":"31-07-2013", "count":"19"},
{"assignedTo":"185271", "createdDate":"24-07-2013", "count":"2"},
{"assignedTo":"185271", "createdDate":"23-07-2013", "count":"1"}
]
}
Now I want to make one json array from the above with the value of data to another json
which will be like:
[
{
key: "0",
values: [["23-07-2013", 2]]
},
{
key: "182398",
values: [["01-08-2013", 2],
["23-07-2013", 2],
["24-07-2013", 12],
["22-07-2013", 1],
["30-7-2013", 4],
["31-7-2013", 19]
},
{
key: "185271",
values: [["24-07-2013", 2],
["23-07-2013", 1]
}
]
I have tried like the following:
for (i in res.data) {
for (k in res.data[i]) {
time_val += "[" + res.data[i]['createdDate'] + ","
+ res.data[i]['count'] + "],";
cumulative_val += '{key:"' + res.data[i]['assignedTo']
+ '",values:'+time_val+'},';
}
}
Could you please guide me how to do this?
Thanks in advance.
Something like this in javascript:
var res = {"status":"Success","data":[{"assignedTo":"0","createdDate":"23-07-2013","count":"2"},
{"assignedTo":"182398","createdDate":"01-08-2013","count":"2"},
{"assignedTo":"182398","createdDate":"23-07-2013","count":"2"},
{"assignedTo":"182398","createdDate":"24-07-2013","count":"12"},
{"assignedTo":"182398","createdDate":"22-07-2013","count":"1"},
{"assignedTo":"182398","createdDate":"30-07-2013","count":"4"},
{"assignedTo":"182398","createdDate":"31-07-2013","count":"19"},
{"assignedTo":"185271","createdDate":"24-07-2013","count":"2"},
{"assignedTo":"185271","createdDate":"23-07-2013","count":"1"}]
}
//Wanted mixed object
var temp = [];
//Store keys, so we do not need to check from temp if key allready exists
var temp_keys = {};
//Loop trough data
for (var i in res.data)
{
//Check if key is allready stored in object
if (!temp_keys[res.data[i]['assignedTo']])
{
//Store new key, and save it''s position
temp_keys[res.data[i]['assignedTo']] = temp.length;
//Create new array element as new object
temp.push(
{
'key' : res.data[i]['assignedTo'],
'values': []
}
);
}
//Save values into correct position
temp[temp_keys[res.data[i]['assignedTo']]]['values'].push([res.data[i]['createdDate'], res.data[i]['count']]);
}
console.log(temp);
console.log(JSON.stringify(temp));
JSON Example Output:
[{"key":"0","values":[["23-07-2013","2"]]},{"key":"182398","values":[["01-08-2013","2"],["23-07-2013","2"],["24-07-2013","12"],["22-07-2013","1"],["30-07-2013","4"],["31-07-2013","19"]]},{"key":"185271","values":[["24-07-2013","2"],["23-07-2013","1"]]}]
use these functions
json_decode
get_object_vars
I guess that the cumulative_key is in the wrong loop:
lastKey = res.data[0]['assignedTo'];
for(i in res.data) {
if(res.data[i]['assignedTo'] != last) {
cumulative_val += '{key:"'+res.data[i]['assignedTo']+'",values:'+time_val+'},';
}
time_val += "["+res.data[i]['createdDate']+","+res.data[i]['count']+"],";
}
You should think about manipulate real array object and then after make a json encoding.
Try this code...
var _root = new Array();
for (i in res.data) {
for (k in res.data[i]) {
var _child = [res.data[i]['createdDate'], res.data[i]['count']];
var _parent = [{"key":res.data[i]['assignedTo'], "values": _child}];
}
_root.push(_parent);
}
var _JSON_ = JSON.stringify(_root);
A slightly different solution just for the sake of variety
let res = {
"status": "Success", "data": [
{"assignedTo": "185271", "createdDate": "23-07-2013", "count": "1"},
{"assignedTo": "182398", "createdDate": "01-08-2013", "count": "2"},
{"assignedTo": "182398", "createdDate": "23-07-2013", "count": "2"},
{"assignedTo": "182398", "createdDate": "24-07-2013", "count": "12"},
{"assignedTo": "185271", "createdDate": "24-07-2013", "count": "2"},
{"assignedTo": "182398", "createdDate": "22-07-2013", "count": "1"},
{"assignedTo": "0", "createdDate": "23-07-2013", "count": "2"},
{"assignedTo": "182398", "createdDate": "30-07-2013", "count": "4"},
{"assignedTo": "182398", "createdDate": "31-07-2013", "count": "19"},
]
};
let values = [];
let ctrl = '';
let interim = {};
for (const obj of res.data) {
const id = obj.assignedTo;
values = interim[obj.assignedTo] ? interim[obj.assignedTo].values : [];
values.push([obj.createdDate, obj.count])
interim[obj.assignedTo] = {"key": obj.assignedTo, "values": values};
ctrl = ctrl !== id ? id : ctrl;
}
let reshaped = Object.values(interim);
console.log(JSON.stringify(reshaped, null, 0));
and the result is
[{"key": "0", "values": [["23-07-2013", "2"]]},
{"key": "182398", "values": [["01-08-2013", "2"],
["23-07-2013", "2"],
["24-07-2013", "12"],
["22-07-2013", "1"],
["30-07-2013", "4"],
["31-07-2013", "19"]]},
{"key": "185271", "values": [["23-07-2013", "1"],
["24-07-2013", "2"]]}
]
I "shuffled" the input data a bit just to avoid a mistake of assuming the data is always sorted... which I almost fell into twice while was writing up this snippet.

Categories

Resources