Stringify JSON differently on each level - javascript

In order to hash (sha1) a JSON and to compare the resulting hash to a given one, I need a String which is exactly the same as the one that has been used to create the given hash.
Then, my stringified JSON must have different indentation for sub nodes of the JSON :
I want this js object :
{id:4,name:'patrick',roles:[{id:1,name:'admin'},{id:2,name:'author'}]}
to be stringified like that :
"{
"id": "4",
"name": "patrick",
"roles": [
{"id":1,"name":"admin"},
{"id":2,"name":"author"}
]
}"
JSON.stringify(obj,null,4) gives me something very near from the solution but not exactly :
"{
"id": 4,
"name": "patrick",
"roles": [
{
"id": 1,
"name": "admin"
},
{
"id": 2,
"name": "author"
}
]
}"
I'm trying with the second argument of JSON.stringify but can not reach my goal :'(

Related

A better way to visualize API response normalized with "Normalizr"

I have this normalized API response :
{
"result": "123",
"entities": {
"articles": {
"123": {
"id": "123",
"author": "1",
"title": "My awesome blog post",
"comments": [
"324"
]
}
},
"users": {
"1": {
"id": "1",
"name": "Paul"
},
"2": {
"id": "2",
"name": "Nicole"
}
},
"comments": {
"324": {
"id": "324",
"commenter": "2"
}
}
}
}
Are there any better ways to visualize/log/debug (an already normalized or while normalizing) a response other than console.log() used with JSON.stringify() ?
There are actually many NPM modules like pretty-print-json or json-beautify that can do this for you as well al libraries, although my favorite method for pretty-printing is still the console.log() paired with JSON.stringify() because you can easily use the remaining arguments for beautify in console.
JSON.stringify() provides you a replacer and a space args:
The replacer allows you to keep in the stringified object the attributes that you want, so he finds in place the attribute and keeps it in the string;
The space defines the tabulation, is used to insert white space into the output JSON string for readability purposes only.

Remove special characters from a specific JSON object in JSON payload

I have a large JSON payload and I want to format, the specific object of the payload using JS.
I want flightdetails array object to edit and remove the special characters from it. How can I achieve this?
I have been working on this using XSLT for the past 2 days, and I went nowhere hence I decided to remove it using JS.
Example of the array(there can be more than 30 records inside the flightdetails)
"flightdetails": [
{
"id": XF-2092,
"trips": 2,
"categories": {
"flights": [
"\"return\",\"oneway\""
]
},
"id": XF-2093,
"trips": 1,
"categories": {
"flights": [
"\"return\""
]
}
}
]
Expected Output
"flightdetails": [
{
"id": XF-2092,
"trips": 2,
"categories": {
"flights": [
"return","oneway"
]
},
"id": XF-2093,
"trips": 1,
"categories": {
"flights": [
"return"
]
}
}
]
The flightdetails object inside the //destinations/flightdetails path

Working With Dynamic Multidimensional key-value pairs in JSON

Having a thorny problem and only see similar but also simpler solutions on SO.
Is is possible to generate a dynamic key AND dynamic values using JS/JSON?
For instance, let's say I have JSON like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
I need to go into the fields and for each field (products, wines, fruits) see if a given service is contained within so that I can go back and generate a product or wine or fruit for each service that requires it. But I don't want to repeat the services names more than once. The resulting JSON should look something like this:
{"svc1":["Products"], "svc2":["Products"], "svc3":["Products"], "svc4":["Fruits", "Wines"]}
The hope would be that to generate a dynamic list in Angular I can just turn and loop back through this JSON, pulling out the values for each product, fruit, wine, whatever.
I've been trying a lot of nested for loops and the like but whenever I get more than one layer down the dynamism seems to stop. I'm guessing that for this to work I need to move between JS Objects and JSON?
Right now I'm trying something like this, which isn't quite working, stringify or no. And maybe I'm flip-flopping too much between JSON and JS Objects:
var outObj = [];
var fieldItems;
$.each(jsonObj.custom.fields, function(key, item) {
fieldItems = item;
fieldItems.name = item.name;
$.each(fieldItems.services, function(key, item) {
var serviceName = item;
//check to see if the serviceName already exists
if (outObj.indexOf(serviceName) > -1) {
outObj.serviceName.push(fieldItems.name);
} else {
outObj.push(serviceName);
}
});
});
JSON.stringify(outObj);
console.log("outObj " + outObj);
I get "can't read property 'push' of undefined" errors and the like. Seems this should be possible from a single nested loop, but maybe I need to just do two passes? Any other suggestions?
To me it sounds like overcomplicated solution. You can use basic array methods of javascript to filter out required structure. I am not sure what profiling_value in the presented snippet, so I started from the object structure in OP
var desiredResult = jsonObj.custom.services.reduce(function(result, service){
result[service.name] = jsonObj.custom.fields.filter(function(field){
return field.services.indexOf(service.name) >= 0;
}).map(function(field){ return field.name; });
return result;
}, {});
This gives the expected result for mentioned object.
reduce is required to iterate over all services and accumulate result in one object. Then for each service fields are iterated to filter out only those that contain link to this service. And finally list of filtered fields is transformed (map) into list of strings - their names - and inserted into accumulator

How to parse string representation of PHP associative array and convert to JSON

I have a string containing a PHP associative array like this, stored in a javascript variable:
[
"id" => "1",
"name" => "Blah",
"data" => [
[
"id" => "25",
"type" => "email",
"data" => "admin#example.com",
],
[
"id" => "32",
"type" => "url",
"data" => "http://example.com",
],
],
]
This string is stored in a variable in my JS script. I want to parse this and convert it into JSON format. How would I go about parsing this? I couldn't find anything useful online as every result pertaining to JSON and PHP always gets me answers pertaining to using json_encode() with PHP or JSON.parse() with JS which is definitely not what I want to do.
I assume I need to do somekind of scanner type loop but I'm not sure how to go about doing this. Ideally sections containing keys are parsed as being JSON objects. This is the kind of output I would expect:
{
"id": "1",
"name": "Blah",
"data": [
{
"id": "25",
"type": "email",
"data": "admin#example.com",
},
{
"id": "32",
"type": "url",
"data": "http://example.com",
},
],
}
Thanks

Backbone , changing models attributes

In a collection i need to set the value to one of attributes, but i cant find the way how do it
products.models[i].set({'category.name':'some_value'})
the rest api looks like this
{
"category": {
"id": 3,
"name": "Drink",
"icon": "staging/main/category/icon-drinks.png"
},
"id": 1,
"name": "Sugar54",
"dashboard": 1,
"last_buy": "2013-10-02",
"price": "102",
"buy_period": 7
},
How do i do that ?
If you have complex nested models, I suggest you take a look at BackboneRelational.
Otherwise in your case, you should be fine with
products.models[i].get('category').name = 'some_value';
supposing that category is a normal object.

Categories

Resources