I have multiple json Objects
json1 = [
{'category_id':1,'name':'test1' },
{'category_id':1,'name':'test2' },
{'category_id':1,'name':'test3' },
{'category_id':2,'name':'test2' },
{'category_id':3,'name':'test1' }
];
json2 = [{'category_id':1,'type':'test1'}];
json3 = [
{'category_id':1,'color':'black'},
{'category_id':2,'color':'black'},
{'category_id':3,'color':'white'}
];
I am expecting output like this
final = [
{'category_id':1,'name':'test1','type':'test`','color':'black' },
{'category_id':1,'name':'test2','type':'test`','color':'black' },
{'category_id':1,'name':'test3','type':'test`','color':'black' },
{'category_id':2,'name':'test2','color':'black' },
{'category_id':3,'name':'test1','color':'white' }
];
As i have long json object. Looping is good idea or not ? Does there is any inbuilt function for doing the same.
Using underscore you can achieve it via:
Demo Fiddle
var jsons = [json1, json2, json3];
var final = {};
// merge all data
_.each(jsons, function (jsonArr) {
_.each(jsonArr, function (json) {
final[json.category_id] = _.extend({}, final[json.category_id], json);
});
});
// map it back onto json1
var finalArr = _.map(json1, function (json) {
return final[json.category_id];
});
console.log(finalArr);
Final value of finalArr:
Here is how you can do the same in plain javascript. :)
var final = {};
var jsons = [json1, json2, json3];
for(var i=0;i<jsons.length;i++){
final[i]=jsons[i];
}
Fiddle
EDIT:
Well, you will have to do it programmatically!
Related
I passed the following object:
var myVar = { typeA: { option1: "one", option2: "two" } }
I want to be able to pull out the key typeA from the above structure.
This value can change each time so next time it could be typeB.
So I would like to know if there is any way to do that
I was able to solve using 'keys'
for a json example like this:
{
"1-0001": {
"name": "red",
"hex": "FF0000"
},
"1-0002": {
"name": "blue",
"hex": "0000FF"
},
"1-0003": {
"name": "green",
"hex": "008000"
}
}
I was able to use
Map<String, dynamic> decoded = json.decode(jsonString);
for (var colour in decoded.keys) {
print(colour); // prints 1-0001
print(decoded[colour]['name']); // prints red
print(decoded[colour]['hex']); // prints FF0000
}
To get all filenames you can use:
var data = ...
var filenames = [];
for(var i = 0; i < data.length; i++) {
var item = data[0]['files'];
var key = item.keys.first;
var filename = item[key]['filename'];
filenames.add(filename);
}
print(filenames);
You need to define a data type.
It is basically a map of (key value-pair) where key is changed as stated in question typeA or typeB
This Object has 2 properties option1 and option2 which is also strings.
Here is the sample code to construct model and how to use it
import 'package:TestDart/TestDart.dart' as TestDart;
main(List<String> arguments) {
var map = new Map<String, MyObject>();
map['typeA'] = new MyObject("one", "two");
map['typeB'] = new MyObject("one", "two");
print(map['typeA'].toString());
print(map['typeA'].toString());
}
class MyObject {
String _option1;
String _option2;
MyObject(this._option1, this._option2);
String get option2 => _option2;
String get option1 => _option1;
#override
String toString() {
return 'MyObject{option1: $_option1, option2: $_option2}';
}
}
Relevant answer
map.forEach((key, value) {
print("Key : ${key} value ${value}");
});
I have JSON of this format
[
{"name":"universityID","value":"454"},
{"name":"grade","value":"88"},
{"name":"date","value":"15-Jan-2016"},
{"name":"address","value":"Washington"}
]
I want my JSON into
{
"universityID":"454",
"grade":"88",
"date":"15-Jan-2016",
"address":"Washington"
}
You just iterate on your array and stuff each attribute into a new object as they come:
var input = [
{"name":"universityID","value":"454"},
{"name":"grade","value":"88"},
{"name":"date","value":"15-Jan-2016"},
{"name":"address","value":"Washington"}
];
var output = {};
input.forEach(function(attr) {
output[attr.name] = attr.value;
});
console.log(output);
EDIT: If universityID needs to be an array:
var input = [
{"name":"universityID","value":"454"},
{"name":"grade","value":"88"},
{"name":"date","value":"15-Jan-2016"},
{"name":"address","value":"Washington"}
];
var output = {};
input.forEach(function(attr) {
if (attr.name == "universityID") {
if (!(attr.name in output)) output[attr.name] = [];
output[attr.name].push(attr.value);
} else {
output[attr.name] = attr.value;
}
});
console.log(output);
I want to define my mongoose schema from JSON file. This is my JSON file structure:
{
"default": [
{
"item": "productTitle",
"label": "Product Title",
"note": "e.g Samsung GALAXY Note 4",
"type": "text",
"required": "Product Name cannot be blank..."
},
{
"item": "productCode",
"label": "Product Code",
"type": "text",
"required": "Product Code cannot be blank..."
}
]}
This is my node.js model:
// Load the module dependencies
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var fs = require('fs');
var file = __dirname + '/product.server.model.json';
// Read the json file
fs.readFile(file, 'utf8', function (err, data) {
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
productJson[data.default[i].slug] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
});
// Define a new 'ProductSchema'
var ProductSchema = new Schema(
// Here I want to put JSON Data 'productJson'
);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
I tried every possible way to define mongoose schema from JSON data 'productJson'. But unless I pre-define my mongoose schema, it is not working. Is there any way to define mongoose schema from JSON data in my model? Any suggestion please?
fs.readFile is an asynchronous function which means that it returns immediately and then later provides its results to the caller via the callback function that you provide as the third parameter.
As such, you need to hold off on using productJson until its populated within that callback. That means moving your schema and model creation inside the callback as well.
fs.readFile(file, 'utf8', function (err, data) {
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
// Changed .slug to .item here as I don't see slug in the JSON
productJson[data.default[i].item] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
// Define a new 'ProductSchema'
var ProductSchema = new Schema(productJson);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
});
Another alternative you can use here is to use the synchronous fs.readFileSync method to read the file instead. This is helpful in startup/initialization cases like this where your application as a whole shouldn't proceed until this file is processed.
var data = fs.readFileSync(file, 'utf8');
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
// Changed .slug to .item here as I don't see slug in the JSON
productJson[data.default[i].item] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
// Define a new 'ProductSchema'
var ProductSchema = new Schema(productJson);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
I am trying to add an object in an array to an item in a JSON object.
The result I am looking for is:
{ "AvailableFacets":[ "color", "sheenlevel" ],
"Selections":[
{ "Facet":"color", "Value":"red" },
{ "Facet":"color", "Value":"blue" }
]
}
but I get the error "TypeError: myJsonObject.Selection.push is not a function" when doing the following:
var testJson = function () {
var myJsonObject = $.parseJSON('{"AvailableFacets":["color", "sheenlevel"]}');
myJsonObject.Selection = "[]";
var newObject1 = $.parseJSON('{"Facet":"color", "Value":"red"}');
var newObject2 = $.parseJSON('{"Facet":"color", "Value":"blue"}');
myJsonObject.Selection.push(newObject1);
return myJsonObject;
};
What am I doing wrong?
"[]" !== []. Did that help? You are using the wrong types. Also you are looking for an output with "Selections" but you are attempting to define "Selection", but I assume that is a typo. This should work:
myJsonObject.Selection = [{"Facet":"color", "Value":"red"},{"Facet":"color", "Value":"blue"}];
But if you wanted to parse a string of JSON as JSON then just change
myJsonObject.Selection = "[]";
to:
myJsonObject.Selection = [];
I have a complex JSON Object like this:
var requestData = { __batchRequests: [ { __changeRequests: [
{ requestUri: "Customers", method: "POST", headers: { "Content-ID": "1" }, data: {
CustomerID: 400, CustomerName: "John"
} }
] } ] };
I am trying to do two things:
Declare this object but with the variable data empty
With a loop, add items dynamically to the data object,
How can I do it?
This isn't too complex an object. And it isn't JSON until it's converted into a string.
Right now, it's just plain-ol' JS objects and arrays.
Breaking that down into its elements might look like this:
var requestData = {};
requestData.__batchRequests = [];
requestData.__batchRequests[0] = {};
requestData.__batchRequests[0].__changeRequests = [];
requestData.__batchRequests[0].__changeRequests[0] = {};
requestData.__batchRequests[0].__changeRequests[0].requestUri = "Customers";
requestData.__batchRequests[0].__changeRequests[0].method = "POST";
requestData.__batchRequests[0].__changeRequests[0].headers = { "Content-ID" : "1" };
requestData.__batchRequests[0].__changeRequests[0].data = {};
Aside from the repeats, what do you see?
Personally, I see that __changeRequests[0] is an object as simple as:
var changeRequest = {
requestUri : "Customers",
method : "POST",
headers : { "Content-ID" : "1" },
data : {}
};
I also see that I can just push that onto my array of change requests:
requestData.__batchRequests[0].__changeRequests.push(changeRequest);
Right?
I also know that my changeRequest variable still points to the one that I just added to the array, and whatever I change on the object will show up as changed in the array's reference to the object, too:
changeRequest.data.CustomerName = "Bob";
changeRequest.data.CustomerID = "204";
requestData.__/*...*/changeRequests[0].data.CustomerName; // Bob
So how about writing yourself some helper-functions?
function extend (obj, additions) {
var key;
for (key in obj) { if (additions.hasOwnProperty(key)) {
obj[key] = additions[key];
}
}
function makeChangeRequest (url, method, headers, data) {
var request = {
requestUri : url,
method : method,
headers : {},
data : {}
};
extend(request.headers, headers);
extend(request.data, data);
return request;
}
function getBatch (num) { return requestData.__batchRequests[num]; }
var changeReq = makeChangeRequest("Customers",
"POST",
{ "Content-ID" : "1" },
{ CustomerName : "Bob", CustomerID : "2012" });
var batch = getBatch(0);
batch.__changeRequests.push(changeReq);
If you want to add more data to changeReq.data later:
extend(changeReq.data, { Address : "33 Nowhere Rd.", City : "Splitsville" });
For the first part of your question, you can initialize data with an empty associative array:
var requestData = { __batchRequests: [ { __changeRequests: [
{ requestUri: "Customers", method: "POST", headers: { "Content-ID": "1" }, data: {} }
] } ] };
This next part assumes, perhaps incorrectly, that you can use jQuery. It also assumes that you have an array containing all of the relevant key value pairs.
var customerDeetsArray =[{CustomerID: 400}, {CustomerName: "John"}];
for (var i in customerDeetsArray) {
requestData.data = $.extend(requestData.data, customerDeetsArray[i]);
}
See working example which makes use of console.debug:
http://jsfiddle.net/4Rh72/6/