How to generate minimum-size Javascript object? - javascript

How can I create a minimum-sized Javascript serialization of a Javascript object? Essentially a JSON.stringify with all unnecessary quotes removed. (Only basic JSON data types need to be supported, not Dates etc.)
For example, the JSON:
{
"pi": 3.14,
"e!": 4.26
}
would become:
{pi:3.14,"e!":4.26}
Edit: The result is not valid JSON, but is valid Javascript.

Copied from https://stackoverflow.com/a/11233515/916000 and modified:
function stringify(obj_from_json) {
if (typeof obj_from_json !== "object") {
return JSON.stringify(obj_from_json);
} else {
if (Array.isArray(obj_from_json)) {
// if the array contains an object
var arr = [];
for (var i = 0, len = obj_from_json.length; i < len; i++) {
arr.push(stringify(obj_from_json[i]));
}
return "[" + arr.join(",") + "]";
} else {
var props = Object
.keys(obj_from_json)
.map(function(key) {
return (new RegExp(/^[1-9a-zA-Z_$][a-zA-Z0-9_$.]*$/).test(key) ? key : "\"" + key + "\"") + ":" + stringify(obj_from_json[key]);
}).join(",");
return "{" + props + "}";
}
}
}
console.log(stringify({
"pi": 3.14,
"e!": 4.26
}));
console.log(stringify([{
"adjacencies": [{
"nodeTo": "graphnode2",
"nodeFrom": "graphnode1",
"data": {
"$color": "#557EAA"
}
}],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode1",
"name": "graphnode1"
}, {
"adjacencies": [],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode2",
"name": "graphnode2"
}]));
console.log(stringify({1: 2}));
console.log(stringify({"000": 42}));
console.log(stringify({1.26: 42}));
Edit: Added object array support.
Edit: Fixed array conversion.

Related

how to get data from dynamic key pair value in Angular

here my issue i unable to get the dynamic key pair value from the dynamic json
below is my json
var d = {
"pexels-photo.jpeg": {
"information": "laptop",
"desc": {
"mimetype": "image/jpeg",
"id": "shsj44",
"file_id": "pexels-photo.jpeg"
},
"_id": "shsj44"
}
}
here i tried below
Object.keys(d).forEach(function(key){
var value = d[key];
console.log(key + ':' + value) ;
});
i want to get the id value "_id" & "file_id" values
You can use Destructuring assignment
var d = {"dynamic": {"information": "laptop","desc": { "mimetype": "image/jpeg","id": "shsj44","file_id": "pexels-photo.jpeg" },"_id": "shsj44"}}
let dynamicKey = Object.keys(d)[0]
let {[dynamicKey]:{desc:{
file_id
},_id}} = d
console.log(file_id, '\n', _id)
That is because of the + before the value, which will try to concatenate the value and you will see [object object]
var d = {
"pexels-photo.jpeg": {
"information": "laptop",
"desc": {
"mimetype": "image/jpeg",
"id": "shsj44",
"file_id": "pexels-photo.jpeg"
},
"_id": "shsj44"
}
}
Object.keys(d).forEach(function(key) {
let value = d[key];
console.log(key + ' : ', value);
console.log(key + ' : ', value.desc.id);
});
You need to check whether the value is object or not, if yes then you need to loop over it again.
Following code will print every key-value pair in d
export class AppComponent implements OnInit {
d = {
'pexels-photo.jpeg': {
'information': 'laptop',
'desc': {
'mimetype': 'image/jpeg',
'id': 'shsj44',
'file_id': 'pexels-photo.jpeg'
},
'_id': 'shsj44'
}
};
ngOnInit(): void {
this.calc(this.d);
}
calc(val) {
Object.keys(val).forEach(key => {
const value = val[key];
if (typeof (value) === 'object') {
this.calc(value);
} else {
console.log(key + ':' + value);
}
});
}
}
Try this :
var d = {
"pexels-photo.jpeg": {
"information": "laptop",
"desc": {
"mimetype": "image/jpeg",
"id": "shsj44",
"file_id": "pexels-photo.jpeg"
},
"_id": "shsj44"
}
};
Object.keys(d).filter(key => {
Object.keys(d[key]).filter(item => {
if (item === 'desc') {
Object.keys(d[key][item]).filter(elem => {
if ((elem === 'id') || (elem === 'file_id')) {
console.log(elem + ' : ' + d[key][item][elem]);
}
});
}
})
});

How to stringify an Object which includes objects of array?

How to manipulate this object to URL query parameter.The example the the query parameter should be
advocates=7195&categories=25&checkbox-active=true&checkbox-close=undefined&checkbox-filed=true&checkbox-notFiled=undefined&cities=Delhi&cities=mumbai
Here is the code to convert any json no matter how deep it is into query params:
var o = {
"stage": 50,
"categories": [25, 23, 28],
"advocates": [{
"key": "7195",
"label": "kallol saikia"
}],
"cities": [{
"key": 390,
"label": "Delhi"
}, {
"key": 6,
"label": "Mumbai"
}],
"checkbox-filed": true,
"checkbox-active": true
}
function getParams(key, value) {
var queries = [];
var newKey;
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
newKey = key + "[" + i + "]";
queries = queries.concat(getParams(newKey, value[i]));
}
} else if (value && typeof value === 'object' && value.constructor === Object) {
for (var prop in value) {
if (value.hasOwnProperty(prop)) {
newKey = key ? key + "[" + prop + "]" : prop;
queries = queries.concat(getParams(newKey, value[prop]));
}
}
} else {
queries.push(key + "=" + value);
}
return queries;
}
var query = getParams("", o).join("&");
console.log(query);
I hope this solves your issue.
Maybe:
var o = {
'advocates': [{
key: 1
}],
'checkbox-active': true
};
var query = Object.keys(o).map(function(i) {
var val;
if (Array.isArray(o[i])) {
val = o[i][0].key;
} else {
val = o[i];
}
return i + '=' + val;
}).join('&');
console.log(query);
You can try using Post Request
Send a JSON String using JSON.Parse() and JSON.stringify()
Convert your params array to JSON String and send that as a single query param.
Decode the query string param (i.e JSON string)
Adding Example
var jsonString = JSON.stringify({
"stage": 50,
"categories": [25, 23, 28],
"advocates": [{
"key": "7195",
"label": "kallol saikia"
}],
"cities": [{
"key": 390,
"label": "Delhi"
}, {
"key": 6,
"label": "Mumbai"
}],
"checkbox-filed": true,
"checkbox-active": true
});
// Pass down the Encoded Json
var encodedJson = encodeURI(jsonString);
console.log(encodedJson);
// Decode Json
var decodedJson = decodeURI(encodedJson);
var decodedObject = JSON.parse(decodedJson);
console.log(decodedObject);
Output
"%7B%22stage%22:50,%22categories%22:%5B25,23,28%5D,%22advocates%22:%5B%7B%22key%22:%227195%22,%22label%22:%22kallol%20saikia%22%7D%5D,%22cities%22:%5B%7B%22key%22:390,%22label%22:%22Delhi%22%7D,%7B%22key%22:6,%22label%22:%22Mumbai%22%7D%5D,%22checkbox-filed%22:true,%22checkbox-active%22:true%7D"
Object { stage: 50, categories: Array [25, 23, 28], advocates: Array [Object { key: "7195", label: "kallol saikia" }], cities: Array [Object { key: 390, label: "Delhi" }, Object { key: 6, label: "Mumbai" }], checkbox-filed: true, checkbox-active: true }
This algorithm will work. Just with caution, if you change the object structure, this might break
Hope this helps :>
var obj = {
"stage": 50,
"categories": [25, 23, 28],
"advocates": [{
"key": "7195",
"label": "kallol saikia"
}],
"cities": [{
"key": 390,
"label": "Delhi"
}, {
"key": 6,
"label": "Mumbai"
}],
"checkbox-filed": true,
"checkbox-active": true
}
let str = 'advocates=' + obj.advocates[0].key +
'&categories=' + obj.categories[0] +
'checkbox-active=' + obj['checkbox-active'] +
'checkbox-close=' + obj['checkbox-close'] +
'checkbox-filed=' + obj['checkbox-filed'] +
'checkbox-notFiled=' + obj['checkbox-notFiled'];
obj.cities.forEach(city=>str+= 'cities=' + city.label + '&')
str = str.substring(0,str.length-1)
console.log(str)
advocates=7195&
categories=25&
checkbox-active=true&
checkbox-close=undefined&
checkbox-filed=true&
checkbox-notFiled=undefined&
cities=Delhi&
cities=mumbai
`${key}${i>0?'&':''}${val[0]}=${val[1]}`, ""
'advocates':
'checkbox-active':
'checkbox-close':
'checkbox-filed':
'checkbox-notFiled':
arrStr += key[0] + '=';
arrStr += key[1][0].key + '&';
Here is an example I just made: https://jsfiddle.net/BrandonQDixon/surwf7gd
The script below will loop through the keys of an object and convert them to GET style parameters, which is what your request looks like. I made it a function so you can directly call it on an object.
This will also work recursively, if your object has nested objects, but understand that if nested objects have some of the same keys (or there are duplicates in general), they will both be added to the string.
/**
* This will turn an object into a GET style parameter
* This scans recursively if 2nd param is set to true, but "flattens" every property into one string, so this may cause some overriding
* This will encode the keys and values if 3rd param is set to true
*/
function paramatize(obj,recursive = true,encode = true) {
let str = "";
let len = Object.keys(obj).length
let i = 0;
for (let key in obj) {
i++;
if (typeof obj[key] === 'object' && recursive) {
str += paramatize(obj[key]);
} else {
let nKey = (encode)?encodeURIComponent(key):key;
let nValue = (encode)?encodeURIComponent(obj[key]):obj[key];
str += nKey+"="+nValue;
}
if (i < len) {
str += "&";
}
}
return str;
}

How to check if object exist by Id in tab of json object?

I have an array of objects:
var tab = [
{
"id": "1",
"data" : "blabla"
},
{
"id": "2",
"data": "samplesample"
}
]
Are there any simple tools for check if an object exist in this array by id.
Something like :
chekexists(tab, "id", "1") ; // return true
chekexists(tab, "id", "2") ; // return true
chekexists(tab, "id", "3") ; // return false
chekexists(tab, "data", "blabla") ; // return true
chekexists(tab, "data", "toto") ; // return false
Is this possible to perform this with underscore?
For avoid confusion, my tab is load like this :
var tab = JSON.parse(fs.readFileSync('path'));
You can use underscore like below:
function checkexists(array, prop) {
return !!_.where(array, prop).length;
}
Now you can use it like:
checkexists(tab, {id: '1'});
checkexists(tab , "data", "blabla") ;
You can use _.findWhere:
function checkexists(list, props) {
return _.findWhere(list, props) !== undefined;
}
checkexists(tab, {id: 1});
checkexists(tab, {data: 'toto'});
Easy using the open source project jinqJs
var tab = [
{
"id": "1",
"data" : "blabla"
},
{
"id": "2",
"data": "samplesample"
}
]
var result = jinqJs().from(tab).where('id == 2').select();
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
//OR you can do this
result = jinqJs().from(tab).in(['1','2'], 'id').select();
document.body.innerHTML += '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>

Javascript sort method handling null values

I have a list of objects where I want to sort the objects based on a field I know I can use sort methods. When the comparing field have null values, sorting is not happening, how to fix this issue?
http://jsfiddle.net/mailtoshebin/kv8hp/
var arrOfObj = [
{
"Name": "Zak",
"Age": 25
},
{
"Name": "Adel",
"Age": 38
},
{
"Name": null,
"Age": 38
},
{
"Name": "Yori",
"Age": 28
}
];
sortArrOfObjectsByParam(arrOfObj, "Name");
alert("ASCENDING: " + arrOfObj[0].Name + ", " + arrOfObj[1].Name + ", " + arrOfObj[2].Name);
function sortArrOfObjectsByParam(arrToSort , strObjParamToSortBy ) {
if(sortAscending == undefined) sortAscending = true; // default to true
if(sortAscending) {
arrToSort.sort(function (a, b) {
return a[strObjParamToSortBy] > b[strObjParamToSortBy];
});
}
else {
arrToSort.sort(function (a, b) {
return a[strObjParamToSortBy] < b[strObjParamToSortBy];
});
}
}
you can deal with the null values inside the comp func:
arrToSort.sort(function (a, b) {
if (a[strObjParamToSortBy]==null) return 1
if (b[strObjParamToSortBy]==null) return 0
return a[strObjParamToSortBy] > b[strObjParamToSortBy];
});

Change key name in nested JSON structure

I have a JSON data structure as shown below:
{
"name": "World",
"children": [
{ "name": "US",
"children": [
{ "name": "CA" },
{ "name": "NJ" }
]
},
{ "name": "INDIA",
"children": [
{ "name": "OR" },
{ "name": "TN" },
{ "name": "AP" }
]
}
]
};
I need to change the key names from "name" & "children" to say "key" & "value". Any suggestion on how to do that for each key name in this nested structure?
I don't know why you have a semicolon at the end of your JSON markup (assuming that's what you've represented in the question), but if that's removed, then you can use a reviver function to make modifications while parsing the data.
var parsed = JSON.parse(myJSONData, function(k, v) {
if (k === "name")
this.key = v;
else if (k === "children")
this.value = v;
else
return v;
});
DEMO: http://jsfiddle.net/BeSad/
Try this:
function convert(data){
return {
key: data.name,
value: data.children.map(convert);
};
}
Or if you need to support older browsers without map:
function convert(data){
var children = [];
for (var i = 0, len = data.children.length; i < len; i++){
children.push(convert(data.children[i]));
}
return {
key: data.name,
value: children
};
}
You could use a function like this :
function clonerename(source) {
if (Object.prototype.toString.call(source) === '[object Array]') {
var clone = [];
for (var i=0; i<source.length; i++) {
clone[i] = goclone(source[i]);
}
return clone;
} else if (typeof(source)=="object") {
var clone = {};
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
var newPropName = prop;
if (prop=='name') newPropName='key';
else if (prop=='children') newPropName='value';
clone[newPropName] = clonerename(source[prop]);
}
}
return clone;
} else {
return source;
}
}
var B = clonerename(A);
Note that what you have isn't a JSON data structure (this doesn't exist as JSON is a data-exchange format) but probably an object you got from a JSON string.

Categories