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.
Related
I make json validation with ajv. I need to validate array of strings. I know which elements can be placed there so I make appropriate 'enum'. But in some case enum can be empty and array can be empty too. Here is simple test:
var schema = {
"type":"array",
"items" : {
"type" : "string",
"enum" : []
}
}
var data = [];
var Ajv = require('./ajv-4.1.1.js');
var ajv = Ajv({
allErrors : true
});
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid)
console.log(validate.errors);
As a result I get:
Error: schema is invalid:data.items.enum should NOT have less than 1 items, data.items should be array, data.items should match some schema in anyOf
I can add any fictive string to enum array but is it possible to validate this case in legal way? Adding 'minItems=0' restriction doesn't help.
Is it really json schema draft restriction that I can't use empty enum?
UPD: I expect to validate code in general case:
var array = Object.keys(someObj); // array: ["foo", "bar"]
var schema = {
"type":"array",
"items" : {
"type" : "string",
"enum" : array
}
}
var data = ["foo"]; // valid
var data = ["bar"]; // valid
var data = ["bar","foo"]; // valid
I expect to validate code in special case:
var array = Object.keys(someObj); // array: []
var schema = {
"type":"array",
"items" : {
"type" : "string",
"enum" : array
}
}
var data = []; // I expect to see it valid too but get error instead.
The enum keyword is required to have at least one value. The specification states ...
5.5.1.1. Valid values
The value of this keyword MUST be an array. This array MUST have at least one element. Elements in the array MUST be unique.
Elements in the array MAY be of any type, including null.
http://json-schema.org/latest/json-schema-validation.html#anchor76
This makes sense because an empty enum would mean nothing would ever validate. However, I do see how it could come in handy in your particular case. If you need to build the schema dynamically, you will need to check for the empty array case and use a different schema.
Here's one way to do it:
{
"type": "array",
"maxItems": 0
}
Here's another:
{
"type": "array",
"not": {}
}
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']
}
I have a parametrized JUnit Class with something similar to this to setup the parametrized data:
#Parameters(name = "{index}: {0}/{1} : {2}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{
"Samsung",
new Object[] { "size", "10" },
"http://my.test.service.com/svc/brand/samsung?size=10"
},
{
"Apple",
new Object[] { "color", "red" },
"http://my.test.service.com/svc/brand/apple?color=red"
},
// Code truncated
});
}
After running the code, I can see the result like this:
[0: Samsung/[Ljava.lang.Object;#713dff89 : http://my.test.service.com/svc/brand/samsung?size=10]
[1: Apple/[Ljava.lang.Object;#23ab8f3f : http://my.test.service.com/svc/brand/apple?color=red]
etc...
This is quite logical as the second element {1} is an array.
Is there any way to get the content of the array?
E.g with a notation like
#Parameters(name = "{index}: {0}/{1[0]}-{1[1]} : {2}")
to get
[0: Samsung/size-10 : http://my.test.service.com/svc/brand/samsung?size=10]
[1: Apple/color-red : http://my.test.service.com/svc/brand/apple?color=red]
I tried to use {1}{0}, {1[0]} and {1.0} but none are working
The name-argument of the Parameters annotation is used as first parameter of a MessageFormat.format(pattern, args...) call.
I couldn't find a hint for formatting arrays in the javadoc of MessageFormat. My solution would be to add a fourth parameter to your list of parameters which contains the desired string.
Collection<Object[]> data = ... // build your data
for (Object[] parameter : data) {
parameter[3] = Arrays.toString((Object[]) parameter[1]);
}
return data;
Is there any way to read an object from a list of objects dynamically with object key.
My complex objects is something like :
$scope.mainObject = {
name : "Some value",
desc : "Some desc",
key1: {
arrayLst: []
},
key2: {
arrayLst: []
}
}
In my method, I have the key value either key1 or key2 in a string keyValue. How can I write to object like :
$scope.mainObject.key1.arrayLst = data;
In the form of something like :
$scope.mainObject.get(keyValue).arrayLst = data;
Well, there's something known as Array notation in JavaScript objects. More on it here.
You can write it something like this :
$scope.mainObject.[keyValue].arrayLst = data;
i am using the extjs. i need to retrieve distinct data from store as per requirement. In my store contains single list not nested list in that have regions like AMERICAS , North Sea and SE Asia. these region it self have subRegion,vesselName and vesselType values. I need to retrive unique value based on region, bacasue it contains many duplicate records. I have tried like as below, but it is not working me. Can anybody tel me how to achieve ?. great appreciated. Thank you.
var vesselStore=Ext.getStore('VesselStatusReportStore');
var arr=new Array();
var obj;
vesselStore.each(function(rec,index)
{
obj=new Object();
if(rec.get('region')=='AMERICAS'){
obj.subRegionAmerica=rec.get('subRegion');
obj.vesselNameAmerica=rec.get('vesselName');
obj.vesselTypeAmerica=rec.get('vesselType');
}
if(rec.get('region')=='NorthSea'){
obj.subRegionNorthSea=rec.get('subRegion');
obj.vesselNameNorthSea=rec.get('vesselName');
obj.vesselTypeNorthSea=rec.get('vesselType');
}
if(rec.get('region')=='SE Asia'){
obj.subRegionSEAsia=rec.get('subRegion');
obj.vesselNameSEAsia=rec.get('vesselName');
obj.vesselTypeSEAsia=rec.get('vesselType');
}
arr.push(obj);
console.log(obj);
});
Json:
[ {
"region" : "AMERICAS",
"startDate" : null,
"subRegion" : "US",
"vesselName" : "Thoma-Sea � Hull #147",
"vesselType" : "PSV"
},
{
"region" : "AMERICAS",
"startDate" : null,
"subRegion" : "US",
"vesselName" : "Thoma-Sea � Hull #148",
"vesselType" : "PSV"
},
{
"region" : "AMERICAS",
"startDate" : null,
"subRegion" : "Mexico",
"vesselName" : "Thoma-Sea � Hull #148",
"vesselType" : "PSV"
}]
It looks like you want to use collect. http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Store-method-collect
vesselStore.collect('region')
This section doesn't make sense:
obj=new Object();
if(rec.get('region')=='AMERICAS'){
obj.subRegionAmerica=rec.get('subRegion');
obj.vesselNameAmerica=rec.get('vesselName');
obj.vesselTypeAmerica=rec.get('vesselType');
}
if(rec.get('region')=='NorthSea'){
obj.subRegionNorthSea=rec.get('subRegion');
obj.vesselNameNorthSea=rec.get('vesselName');
obj.vesselTypeNorthSea=rec.get('vesselType');
}
if(rec.get('region')=='SE Asia'){
obj.subRegionSEAsia=rec.get('subRegion');
obj.vesselNameSEAsia=rec.get('vesselName');
obj.vesselTypeSEAsia=rec.get('vesselType');
}
arr.push(obj);
You are basically saying "Whatever the region is, copy the record to obj, then add that obj to my array".
I believe you meant something more along these lines:
var vesselStore=Ext.getStore('VesselStatusReportStore');
var iRegions = [];
vesselStore.each(function(rec,index)
{
var iRegionName = rec.get('region');
// Make sure theres a array item with the region name,
// if not create a blank array;
iRegions[ iRegionName ] = iRegions[ iRegionName ] || [];
// Add the record to its corresponding array item.
// (If you don't want the full record, you can just get the
// fields individually like you did in your code).
iRegions[ iRegionName ] = rec;
}
console.log( iRegions );