How can I loop through values in my json file? - json

suppose I have a json file and I would like to loop through the values like so:
var myModel = {"id": 0, "date": "2014-10-28", "amount": 1111, "productId": "2", "description": "Cash"};
for (value in myModel)
{
//element(by.model(key)).clear().sendKeys(value);
}
This is a part of a jasmine script but it is not the point. The question is how can I loop through my model per key i.e 'id','date' etc and their values in angular js?

i think you need this:
for (key in myModel) {
console.log("key is :",key)
console.log("value is:",myModel[key])
}

Angular foreach will do the trick
Invokes the iterator function once for each item in obj collection,
which can be either an object or an array. The iterator function is
invoked with iterator(value, key, obj), where value is the value of an
object property or an array element, key is the object property key or
array element index and obj is the obj itself. Specifying a context
for the function is optional.
var values = {"id": 0, "date": "2014-10-28", "amount": 1111, "productId": "2",
"description": "Cash"};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
console.log(log);
Fiddle

Related

Is it possible to add a key to a value that does not have a key in JSON?

I have a JSON without a key but just a value. Is it possible to add a key to it using React?
Here I have the and hanging without a key. How do I add a key to it, so that it's easier to read? I looked at JSON.Stringify and checked the replacer but it does not let me do it. delete also does not let me do it.
{
"sample": [
{
"id": "r-1",
"name": "sam"
},
"and",
{
"id": "r-2",
"name": "jerry"
}
]
}
You're confusing objects and arrays. The "key" with the string and as a value isn't a key. It's an array element (the value of the sample property is an array). It can't have a key unless you convert it from a string to an object, like the array elements before and after it, which are objects.
The structure of the array on the sample object property looks like this:
object | string | object
If you're ok changing your data from a string to an object, just replace the second array element (index 1) in the sample property with a new object:
const myObj = {
"sample": [{
"id": "r-1",
"name": "sam"
},
"and",
{
"id": "r-2",
"name": "jerry"
}
]
}
myObj.sample[1] = {
newKey: myObj.sample[1]
};
console.log(myObj);

Extract value from array of objects in Postman

I want to extract Id value from the array with objects in Postman and then set it as an environment variable. In case JSON response is an object, the following script works, but not with an array of objects (my array has only one object).
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data.Id);
JSON response:
[
{
"Id": 1287,
"LastName": "Trump",
"FirstName": "Donald",
"MiddleName": "Von",
"City": "New York City",
"Phone": "66 77 88",
"State": "New York",
"Fax": "111-222-333",
"ReferenceId": "12345",
"Active": false,
"CurrentWorkingSchemeId": null
}
]
If it is an array of objects, then just select the first object using index [0] before grabbing the object's key like this:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data[0].Id);
This works like charm!
Basically what i am doing here is, parse the response and from the data array, take id and save it in postman environment variable.
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++) `
{
var counter = jsonData.data[i];
postman.setEnvironmentVariable("schID", counter.id);
}

How to check JSON request body for REST Api, for object attributes and structure?

I am writing my first api (express/node) and one of the endpoints receives json data in the body like:
{
"text": "some comment here...",
"tags": [
{"id": 0, "tag": "some tag 1"},
{"id": 123, "tag": "some tag 2"}
],
"date": "1452305028289",
}
Is there some way you can check that all the properties exist on the object and that they have values? Or do you have to write a custom function checking for each required property and values?
You can use one of these packages for validating data with NodeJS:
https://github.com/hapijs/joi
https://github.com/mafintosh/is-my-json-valid
https://github.com/ctavan/express-validator
A simple solution would be this function that takes an object and a list of strings as the properties of that object:
var checkProperties = function (obj, props) {
return props
.map(function(prop) { return obj.hasOwnProperty(prop); })
.reduce(function (p, q) { return p && q; });
}
use like this
checkProperties({ prop1: someValue, prop2: someOtherValue }, ["prop1", "prop2"]); // true

Good way to convert JSON to Array

i am trying to convert a json response to array in action script 3.
This is my JSON response:
[{
"id": 1,
"klistid": 8017,
"name": "List item name",
"description": "List item description",
"type": 1,
"offset": 300,
"req": "gfi"
},
{
"id": 2,
"klistid": 8018,
"name": "List item name",
"description": "List item description",
"type": 1,
"offset": 600,
"req": "gfi"
},
{
"id": 3,
"klistid": 8019,
"name": "List item name",
"description": "List item description",
"type": 1,
"offset": 900,
"req": "gfi"
}]
and this is my ac3 code:
function GetLists()
{
var req:URLRequest = new URLRequest("http://localhost:51318/api/List/1");
var ret:URLLoader = new URLLoader();
ret.addEventListener(Event.COMPLETE,function(e:Event)
{
var jsonData:Object = JSON.decode(ret.data);
for (var i:String in jsonData)
{
trace(i + ": " + jsonData[i]);
}
});
ret.load(req);
}
I assigned this function to a button but whenever i click that button nothing happens. I put traces in ac3 code when it enters the for loop code just stops and does nothing. I just want to convert this json string to an array or list to iterate through in it. I've already seen some posts about converting JSON strings to arrays but i have tried them all still nothing worked yet.
Thanks
There's a difference between your json data and the way to try to iterate on it.
Your data is an array with one element but you try to iterate on that one element like it should contain your objects id:1, 2, 3, etc ... Well of course it doesn't.
Instead remove the wrapper array from your json data or if you don't want to then:
var data:Object = jsonData[0];
for (var i:String in data)
{
trace(i)
}
All you have to do is cast your decoded data as an Array:
function GetLists()
{
var req:URLRequest = new URLRequest("http://localhost:51318/api/List/1");
var ret:URLLoader = new URLLoader();
ret.addEventListener(Event.COMPLETE,function(e:Event)
{
var jsonData:Array = JSON.decode(ret.data) as Array;
for each(var obj:Object in jsonData)
{
trace(obj["id"] + ": " + obj["description"]);
}
}
ret.load(req);
}

Storing a Key Value Array into a compact JSON string

I want to store an array of key value items, a common way to do this could be something like:
// the JSON data may store several data types, not just key value lists,
// but, must be able to identify some data as a key value list
// --> more "common" way to store a key value array
{
[
{"key": "slide0001.html", "value": "Looking Ahead"},
{"key": "slide0008.html", "value": "Forecast"},
{"key": "slide0021.html", "value": "Summary"},
// another THOUSANDS KEY VALUE PAIRS
// ...
],
"otherdata" : { "one": "1", "two": "2", "three": "3" }
}
But, when there is many pairs / items, the string length becomes prohibited,
and I want a compact way, this could be an example:
// --> (1) a "compact" way to store a key value array
{
[
{"slide0001.html", "Looking Ahead"},
{"slide0008.html", "Forecast"},
{"slide0021.html", "Summary"},
// another THOUSANDS KEY VALUE PAIRS
// ...
],
"otherdata" : { "one": "1", "two": "2", "three": "3" }
}
Additionally, I want a way to identify the data as a keyvalue array,
because, I may want to store other data in the same JSON file.
I have these examples:
// --> (2) a "compact" way to store a key value array
{
"keyvaluelist":
[
{"slide0001.html", "Looking Ahead"},
{"slide0008.html", "Forecast"},
{"slide0021.html", "Summary"},
// another THOUSANDS KEY VALUE PAIRS
// ...
],
"otherdata" : { "one": "1", "two": "2", "three": "3" }
}
// --> (3) a "compact" way to store a key value array
{
"mylist":
{
"type": "keyvaluearray",
"data":
[
{"slide0001.html", "Looking Ahead"},
{"slide0008.html", "Forecast"},
{"slide0021.html", "Summary"},
// another THOUSANDS KEY VALUE PAIRS
// ...
]
},
"otherdata" : { "one": "1", "two": "2", "three": "3" }
}
What do you thing, which one do you suggest, do you have another way ?
Thanks.
UPDATE 1: Remove invalid code. Javascript => JSON
UPDATE 2: Add non key value data
UPDATE 3: Replace "[" and "]" for "{" and "}" in each key value pair
So why don't you simply use a key-value literal?
var params = {
'slide0001.html': 'Looking Ahead',
'slide0002.html': 'Forecase',
...
};
return params['slide0001.html']; // returns: Looking Ahead
If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"} is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.
For example:
var data = ["slide0001.html", "Looking Ahead"];
var C_KEY = 0;
var C_VALUE = 1;
var value = data[C_VALUE];
So, now, your data can be:
[
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:
{ meta: { keys: [ "key", "value" ] },
data: [
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
}
... which would then be handled by the parser.
To me, this is the most "natural" way to structure such data in JSON, provided that all of the keys are strings.
{
"keyvaluelist": {
"slide0001.html": "Looking Ahead",
"slide0008.html": "Forecast",
"slide0021.html": "Summary"
},
"otherdata": {
"one": "1",
"two": "2",
"three": "3"
},
"anotherthing": "thing1",
"onelastthing": "thing2"
}
I read this as
a JSON object with four elements
element 1 is a map of key/value pairs named "keyvaluelist",
element 2 is a map of key/value pairs named "otherdata",
element 3 is a string named "anotherthing",
element 4 is a string named "onelastthing"
The first element or second element could alternatively be described as objects themselves, of course, with three elements each.
For use key/value pair in json use an object and don't use array
Find name/value in array is hard but in object is easy
Ex:
var exObj = {
"mainData": {
"slide0001.html": "Looking Ahead",
"slide0008.html": "Forecast",
"slide0021.html": "Summary",
// another THOUSANDS KEY VALUE PAIRS
// ...
},
"otherdata" : { "one": "1", "two": "2", "three": "3" }
};
var mainData = exObj.mainData;
// for use:
Object.keys(mainData).forEach(function(n,i){
var v = mainData[n];
console.log('name' + i + ': ' + n + ', value' + i + ': ' + v);
});
// and string length is minimum
console.log(JSON.stringify(exObj));
console.log(JSON.stringify(exObj).length);