Add object to array in JSON - json

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 = [];

Related

How do I access the information inside the response body of a postman test Get call

Below is a JSON format from the response body
{
"properties":{
"name":"Jake",
"id":123,
"HashData":[
{
"Major":"CS",
"code":234
}
]
}
}
I tried using:
var x = pm.response.json().properties;
console.log(x.HashData); // it returned HashData is [object object]
console.log(x.HashData.code); // it returned undefined
How else can I see or access the data?
And how do you use this in patch as in if you want to change code from 234 to 567?
You need to use the pm object.
Try console.log(x.HashData[0].code);
Your HasData is an array;
pm.test (
"Response HashData has a code.",
function()
{
var data = pm.response.json();
pm.expect(data.properties.HashData[0]).to.have.property('code');
}
);
This if for object but for arrays you need to use the key.
pm.test (
"Response has name property.",
function()
{
var data = pm.response.json();
pm.expect(data.properties).to.have.property('name');
}
);
More test documentation here : https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference/
To change the value you would do something like :
data.properties.HashData[0].code = 567

AngularJS - Create dynamic properties to an object/model from json

OK, we all know this works:
vm.myObject = {
required : "This field requires data",
.....
}
But how can I create that same object dynamically when the property 'keys' and 'values' come from a json file, eg:
json:
[
{ "key" :"required", "value": "This field requires data"},
.....
]
service:
var myObject = {}
DynamicObjSvc.get()
.success(function(data){
data.forEach(function(item){
// pass each key as an object property
// and pass its respective value
?????????
})
.....
UPDATE:
Kavemen was mostly correct, this turned out to be the solution:
var myObject = {};
DynamicObjSvc.all()
.success(function(data){
angular.forEach(data, function(msg) {
myObject[msg.key] = msg.value; <-- his answer was incorrect here
});
$fgConfigProviderRef.validation.message(myObject);
})
.error(function(err){
console.log(err.message);
})
You can use angular.forEach and the bracket notation for setting (and getting) object properties in Javascript
var myObject = {}
DynamicObjSvc.get().success(
function(data) {
angular.forEach(data, function(value, key) {
myObject[key] = value;
});
}
);
See also Working with Objects from MDN
EDIT
I see now that your data is really an array of objects, not just a single object, so yes, the code above could lead you astray.
In any case, the method of setting an object's properties dynamically using the bracket notation is sound; the loop could be reworked to handle your data array as such:
//we have an array of objects now
var myObjects = [];
DynamicObjSvc.get().success(
function(data) {
//for each object in the data array
for(var i = 0; i < data.length; i++) {
//create and populate a new object for the ith data element
var newObject = {};
angular.forEach(data[i], function(value, key) {
newObject[key] = value;
});
//and add it to the overall collection
myObjects.push(newObject);
}
}
);

Json object merge with unqiue id

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!

Nodejs jsonArray parsing

I have a json object i want to get data from it!
here is my json object
"[androidVersionName=2.3.3, androidVersionId=10, androidId=fa0bef4b5a48eacb, mobileModel=sdk, mobileManufacturer=unknown, mobileId=GRI34, mobileProduct=sdk, applicationName=com.example.socketclient, applicationVersionName=1.0, applicationVersionCode=1, applicationState=INACTIVE, screenWidth=480, screenHeight=480, screenDensity=240, screenDensityName=hdpi, atdPackages=com.atd.panberes(1)]"
and here is my code :
var json = JSON.parse(data);
var androidVersionName = data.rowsets['androidVersionName'].row;
console.log(androidVersionName);
and i get this error :
Cannot read property 'androidVersionName' of undefined
how can i parse data from this jsonObject?
A valid JSON based on your object:
{
"androidVersionName":"2.3.3",
"androidVersionId":10,
"androidId":"fa0bef4b5a48eacb",
"mobileModel":"sdk",
"mobileManufacturer":"unknown",
"mobileId":"GRI34",
"mobileProduct":"sdk",
"applicationName":"com.example.socketclient",
"applicationVersionName":1.0,
"applicationVersionCode":1,
"applicationState":"INACTIVE",
"screenWidth":480,
"screenHeight":480,
"screenDensity":240,
"screenDensityName":"hdpi",
"atdPackages":"com.atd.panberes(1)"
}
You can't parse it to object. But you can transform it to JS object.
var data = "[androidVersionName=2.3.3, androidVersionId=10, androidId=fa0bef4b5a48eacb, mobileModel=sdk, mobileManufacturer=unknown, mobileId=GRI34, mobileProduct=sdk, applicationName=com.example.socketclient, applicationVersionName=1.0, applicationVersionCode=1, applicationState=INACTIVE, screenWidth=480, screenHeight=480, screenDensity=240, screenDensityName=hdpi, atdPackages=com.atd.panberes(1)]";
var result = {};
data.replace(/(\w+)=(\w+)/g, function(_, left, right) { result[left] = right; })
console.log(result);

How to Parse this Json with Json.net?

I have this json:
{
"Message": "The request is invalid.",
"ModelState": {
"Email": [
"The Email field is required."
]
}
}
I want to find the ModelState(if it exists) and then loop through all the errors that re in there.
I can figure out how to do this. I don't want to make a concrete class as the data might change depending on what happens on the sever.
I also can use dynamic as I am on WPF7
JObject jsonObj = JObject.Parse(response.Content);
foreach (var j in jsonObj)
{
var t = j.Value;
}
this is what I have so far.
JObject jsonObj = JObject.Parse(response.Content);
var modelState = jsonObj["ModelState"];
if (modelState != null)
{
// The JSON contains a property called ModelState
// so we can start looping through it:
foreach (JProperty item in modelState)
{
Console.WriteLine(item.Name);
foreach (JValue error in item.Values())
{
Console.WriteLine(error);
}
}
}