Groovy & json: How to get the length of an array from json? - arrays

I am using curl to get some data, then parsing it with JsonSlurper.
The data structure is
"results" : [
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-30"
}
]
So if I'm not mistaken, the entire thing is considered an object. But there is an array in the object (results) which contains objects in that array.
I need to get the length of the results array. When I try to do json.result.length, I receive a null.
How can I get the length of the results array?
def list = ['curl', '-u', 'user:pass', "http://localhost:8081/..."].execute()
def json = new JsonSlurper().parseText(list.text)
println json.result.size()

What I see is, you are using incorrect property to get the size. Need to use results instead of result. Thats is the reason you are seeing that error as result is null(because there is no such property)
Here is working script and gets output as 3:
import net.sf.json.groovy.JsonSlurper
def jsonText='''{
"results" : [
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-30"
}
]
}'''
def json = new JsonSlurper().parseText(jsonText)
println json.results.size()
assert 3 == json.results.size(), "Array size is not matching"

It will be:
def response = ... // your response as text, stream..
def parsed = new JsonSluper().parse(response) // parseText if string
println parsed.results.size()
BTW: size() is for Collection, length for String, note method vs field. In groovy you can use size() for String as well.

{
"projects":
[
{
"platform": "java",
"name":"abc"
},
{
"platform": ".net",
"name":"abcd"
}]
}
for this json file list.json how to get json size or number of applications count.
below code worked for me in groovy as i was using in it my jenkinsfile.
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.io.FileType
def applicationCount()
{
jsonFile1 = 'list.json'
def json1 = readJSON file: jsonFile1
totalApplication = json1.projects.size()
println "count" + totalApplication
println "applicationname" + json1['projects'][0]['name']
}

Related

Array of JSON .count always returns 0 in Swift 4

I got some issues with JSON in swift. When I get JSON data from userDefault storage (Array of JSON as String format) then parse it into JSON object and count number of object in array, but the result always return O (Zero).
My swift code:
let carts = userStorage.object(forKey: userDefaultKeys.carts)
print("logging carts....")
print(JSON(carts as! String).count)
print(JSON(carts as! String))
And it logged into result window
logging carts....
0
[
{
"Lat" : 32,
"Time" : null,
"Items" : [
{
"StorePhone" : "018753678474",
"Ingredient" : "",
"FK_Category" : 2,
"Enabled" : 1,
"UpdatedAt" : null,
"IsActive" : 1,
"quantity" : 1,
}
],
"DeliveryFee" : null,
"Photos" : "https:\/\/networkposting.com\/wpcontent\/uploads\/2018\/02\/maxresdefaul-137.jpg"
}
]
As per the Usage Documentation on the GitHub page:
Initialization
let json = JSON(data: dataFromNetworking)
or
let json = JSON(jsonObject)
or
if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
}
So you can't init a SwiftyJSON object directly via String like you are.
If you have a JSON String... Use the bottom example above to convert it to data first.

Why isn't as3 handing my arrays in JSON?

Here I have this json file.
{
"BnUs5hQZkJWLU9jGlpx9Ifq5ocf2" : {
"bio" : "Your bio!\r",
"birthday" : "Date of Birth?",
"location" : "Location?",
"markerBorder" : 1.5542403222038021E7,
"markerColor" : 8222122.31461079,
"name" : "NamesName?",
"profilePrivacy" : 2,
"sex" : "Gender?",
"privacy" : 2,
"points" : {
"-Kc7lfJk3XbPlNyk-wIR" : {
"address" : "dsfsdfasfsfd",
"description" : "status/desription",
"latitude" : 35.2,
"longitude" : -80.7,
"mediaTargets" : "none",
"pub" : false,
"timestamp" : 1486205926658
},
"aaa" : "aaa"
}
}
}
Those random string of charactors are automatically made when I use firebase.
In this scenario, there might be more "points" I will have to take account for. So when I reference points, I should be talking to an array since it contains both "-Kc7lfJk3XbPlNyk-wIR" (an array) and "aaa" (a string).
So why do I get a type error when trying to convert parsedObject.points into an array?
var parsedObject:Object = JSON.parse(e.target.data);
var multiArray:Array = parsedObject.points;
TypeError: Error #1034: Type Coercion failed: cannot convert Object#5c16089 to Array.
I'm basically trying to do the opposite of what this guy is doing.
Edit: I see in the notes that it only handles string, numbers and Boolean values..
I managed to work around it by adding a "parent" node in the object that duplicates the same value as the name of the entire node so I can reference it in the script. Is there a better way to go about this? Seems pretty redundant.
var parsedObject:Object = JSON.parse(e.target.data);
var myPoints:Object = parsedObject["points"];
//Get all trek names
for each (var key:Object in myPoints)
{
trace("Key = " + key.parent);
trace(parsedObject.treks[key.parent].latitude) //Returns -80.7
}
Because Array is a subclass of Object.
var A:Array = new Array();
var B:Object = new Object();
trace(A is Array); // true
trace(A is Object); // true
trace(B is Array); // false
trace(B is Object); // true
B = new Array(); // nothing wrong here
A = new Object(); // throws exception
So, you might want to tell what kind of data you want to obtain in the Array form from the parsedObject.points Object to proceed.
Alternately, that is how you get actual Array from JSON string:
{
"list": [1,2,3,4,5,6]
}
Looks like it's correctly being parsed by JSON.parse to me.
Arrays in JSON use square brackets, braces are interpreted as objects.
You'd only expect an Array from JSON.parse if you had
"points": [
...
]
whereas this is an Object:
"points": {
...
}
I suggest you look into why you aren't getting [] from your source.

Mongoose update array property

I am trying to update a document via Mongoose, but it does not update the array property.
Here's an example document:
{
"_id" : "55da477a9bfc910e38zzccf2",
"projectname" : "ASong",
"owner" : "adam",
"tracks" : [{
"name" : "Bass",
"file" : "upload/Bass.mp3",
"volume" : "0.75",
"pan" : "0.65"
}, {
"file" : "upload/Drums.mp3",
"volume" : "0.4",
"pan" : "-0.75",
"name" : "Drums"
}
],
"users" : ["adam", "eve"]
}
if I pass to Mongoose an object and try to use it to update like this:
var id = req.body._id;
var editedProject = req.body;
delete editedProject._id;
console.log("TRACKS: " +JSON.stringify(editedProject.tracks));
Project.update({"_id": id}, editedProject, {"upsert": true}, function(err, proj) {
if (err) {
res.send(err);
}
res.json(proj);
});
Only the 1st level properties are updated, but not the array.
I've found some solutions that involve looping through the array elements and calling an update for each element, but I would like to avoid that and keep the update as a single operation.
Or is it better to avoid using arrays?

How to retrieve data from an array [Mongodb]

I am trying to extract data from an array in a collection, the extract of code is shown below:
> db.nodes.findOne()
{
"_id" : NumberLong(24060429),
"_t" : "OsmNode",
"uname" : "studerap",
"uid" : 7260,
"version" : 2,
"changeset" : 634057,
"timestamp" : ISODate("2007-11-27T11:18:58Z"),
"tags" : [
[
"created_by",
"almien_coastlines"
],
[
"source",
"PGS"
]
],
"tagKeys" : [
"created_by",
"source"
],
"location" : [
5.5442938804626465,
-6.488432884216309
]
}
The data i actually want to retrieve is 5.5442938804626465 from the location array. Shall it be retrieved through index?
Thanks for helping
To extract that indexed element of array from all documents, you can get through:
var index = 0, count = 1;
var cursor = db.nodes.find({}, {_id:1, location:{$slice:[index, count]}});
Of course, you can write directly:
var cursor = db.nodes.find({}, {_id:1, location:{$slice:[0, 1]}});
Or
var cursor = db.nodes.find({}, {_id:1, location:{$slice:1}});
Then, extract the result:
var results = [];
cursor.forEach(function(e) {
results.push(e.location[0]);
});
By the way, .find() returns a cursor; and .findOne() returns a document, which is equivalent to running .find().next() once if cursor has documents.

How can i find object from an array in mongoose

I have a schema like following : -
var P = {
s : [{
data : [],
sec : mongoose.Schema.Types.ObjectId
}]
};
Now I want to find only the object of section not entire the row. Like If I pass sec value I want only the value of s.data of that sec object.
example : -
{ s : [
{
data : [],
sec : '52b9830cadaa9d273200000d'
},{
data : [],
sec : '52b9830cadaa9d2732000005'
}
]
}
Result should be look like -
{
data : [],
sec : '52b9830cadaa9d2732000005'
}
I do not want all entire row. Is it possible? If yes, then please help me.
You can use the $elemMatch projection operator to limit an array field like s to a single, matched element, but you can't remove the s level of your document using find.
db.test.find({}, {_id: 0, s: {$elemMatch: {sec: '52b9830cadaa9d2732000005'}}})
outputs:
{
"s": [
{
"data": [ ],
"sec": "52b9830cadaa9d2732000005"
}
]
}
You can always get the value of some field by using find(). For example in your case:
db.collectionName.find({},{s.data:1})
So the first bracket is to apply any condition or query, and in the second bracket you have to define the field as 1(to fetch only those fields value).
Please check http://docs.mongodb.org/manual/reference/method/db.collection.find for more information.
Let me know if it solves your problem.
Not into Mongo or db but working with Pure JavaSript skills here is the Solution as you mentioned Node.js which would do the execution task of the below.
Schema
var P = { s : [
{
data : [],
sec : '52b9830cadaa9d273200000d'
},{
data : [],
sec : '52b9830cadaa9d2732000005'
}
]
};
Search Method Code
var search = function (search_sec){
for (var i=0; i<(P.s.length);i++){
var pointer = P.s[i].sec;
var dataRow = P.s[i];
if((pointer) === search_sec ){
console.log(dataRow);
}
}
};
Here is How you can call - search('search_id');
For example input :
search('52b9830cadaa9d2732000005');
Output:
[object Object] {
data: [],
sec: "52b9830cadaa9d2732000005"
}
Working Demo here - http://jsbin.com/UcobuVOf/1/watch?js,console

Resources