random selection from JSON - json

I try to convert some JSON string data from JSON object into an array.
When I loop over the JSON is it assign the JSON strings into diffrent array cells, eventually I get all the strings from the JSON but in diffrent order in the array each time I run the program.
for (var i:String in data)
{
// get panel tabs and players for each tab
for (var f:String in data[i].tabs)
{
tabsNames.push(f);
}
}
sometimes tabsNames = [ 1,2,3]
sometimes tabsNames = [ 2,3,1] etc'
I cant use sort because I cant know the type of the information that I will get from the JSON.

A JSON object is an unordered set of name/value pairs:
"obj" : {"propA" : "valueA", "propB":"valueB"}
A JSON array is an ordered collection of values:
"arr" : ["propA":"valueA", "propB":"valueB"]
If your data will be stored in JSON Object as list, you always get data in same order.

Related

How can I use a json file if all elements are in one array?

I'm trying to learn to import JSON files into p5.js.
I'm using this list of English words: https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json
I already know how to import things when the entries are organized into respective categories. It seems every entry is in the same array, though. How can I import individual entries?
In this particular case the data you're loading isn't a regular array ([]) with values accessed using an integer index, but a JavaScript Object or associative array({}) with values accessed using a string instead of an integer index.
This is a key-value pair association.
Let's say you have a simple association:
let data = {
"firstName": "Nicholas",
"lastName": "Keough",
}
In the example above firstName and lastName are keys and "Nicholas" and "Keough" are values.
You can use array like [] and instead of an integer index, you'd use the key:
console.log(data["firstName"]);// prints "Nicholas"
console.log(data["lastName"]);// prints "Keough"
alternatively you can use dot notation:
console.log(data.firstName);// prints "Nicholas"
console.log(data.lastName);// prints "Keough"
In your case, let's say dictionary is a variable that holds the loaded JSON data,
you apply the same ideas above to access each word. For example:
console.log(data['absorbent']);//prints 1
or
console.log(data.absorbent.);//prints 1
If you need to loop over the values (and in your case, with the dictionary of 370101 values, you would really want to), you can use a for...in loop.
Alternatively, if you simply need to access the keys, not the values, as a single array you can use Object.keys()
Here's a basic example illustrating both options:
(Bare in mind the dictionary is large so it will take time to load and print the data to console)
let dictionary;
// preload JSON data
function preload(){
dictionary = loadJSON("https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json");
}
function setup(){
noLoop();
console.log('test');
// access JSON data with a for...in loop
for(let word in dictionary){
console.log("word: " + word + " value: " + dictionary[word]);
}
// optionally, access the associative array keys only as an array
console.log(Object.keys(dictionary));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

Get multiple JSON keypair values within a JSON object only if a specific keypair value matches iterable

I am trying to pull multiple json keyvalue data within any given JSON object, from a JSON file produced via an API call, for only the JSON objects that contain a specific value within a keyvalue pair; this specific value within a keyvalue pair is obtained via iterating through a list. Hard to articulate, so let me show you:
Here is a list (fake list representing my real list) I have containing the "specific value within a keyvalue pair" I'm interested in:
mylist = ['device1', 'device2', 'device3']
And here is the json file (significantly abridged, obviously) that I am reading from my python script:
[
{
"name": "device12345",
"type": "other",
"os_name": "Microsoft Windows 10 Enterprise",
"os_version": null
},
{
"name": "device2",
"type": "other",
"os_name": "Linux",
"os_version": null
},
{
"name": "device67890",
"type": "virtual",
"os_name": "Microsoft Windows Server 2012 R2 Standard",
"os_version": null
}
]
I want to iterate through mylist, and for each item in mylist that matches the json keyvalue key "name" in the json file, print the values for 'name' and 'os_name'. In this case, I should see a result where after iterating through mylist, device2 matches the 'name' key in the json object that contains {'name':'device2'}, and then prints BOTH the 'name' value ('device2') and the 'os_name' value ('Linux'), and then continues iterating through mylist for the next value to iterate through the json file.
My code that does not work; let us assume the json file was opened correctly in python and is defined as my_json_file with type List:
for i in mylist:
for key in my_json_file:
if key == i:
deviceName = i.get('name')
deviceOS = i.get('os_name')
print(deviceName)
print(deviceOS)
I think the problem here is that I can't figure out how to "identify" json objects that "match" items from mylist, since the json objects are "flat" (i.e. 'device2' in my json file doesn't have 'name' and 'os_name' nested under it, which would allow me to dict.get('device2') and then retrieve nested data).
Sorry if I did not understand your question clearly, but it appears you're trying to read values off of the list instead of the JSON file since you're looking at i.get instead of key.get when key is what actually contains the information.
And for the optimization issue, I'd recommend converting your list of devices into a set. You can then iterate through the JSON array and check if a given name is in the set instead of doing it the other way. The advantage is that sets can return if they contain an item in O(1) time, meaning it will significantly speed up the overall speed of the program to O(n) where n = size of json array.
for key in my_json_file:
if key.get('name') in my_list:
deviceName = key.get('name')
deviceOS = key.get('os_name')
print(deviceName)
print(deviceOS)

Get json data from var

I gets following data in to a variable fields
{ data: [ '{"myObj":"asdfg"}' ] }
How to get the value of myObj to another variable? I tried fields.myObj.
I am trying to upload file to server using MEANjs and node multiparty
Look at your data.
fields only has one property: data. So fields.myObj isn't going to work.
So, let's start with fields.data.
The value of that is an array. You can see the []. It has only one member, so:
fields.data[0]
This is a string. You seem to want to treat it as an object. It happens to conform to the JSON syntax, so you can parse it:
JSON.parse(fields.data[0])
This parses into an object, so now you can access the myObj property.
JSON.parse(fields.data[0]).myObj
var fields = { data: [ '{"myObj":"asdfg"}' ] };
alert(JSON.parse(fields.data[0]).myObj);

Get value of json string

[
{
"type": "spline",
"name": "W dor\u0119czeniu",
"color": "rgba(128,179,236,1)",
"mystring": 599,
"data": ...
}
]
I am trying to access this json as json['W doręczeniu']['mysting'], and I get no value why is that?
You're trying to access the index "W doręczeniu" but that's not an index it's a value. Also, what you seem to have is an array of JSON objects.
The [ at the start marks the array, the first element of which is your JSON object. The JSON obj begins with the {
You're also trying to use a [ ], but JSON values are accessed with the dot operator.
I'm not sure which index you're actually trying to access, but try something like this:
var x = json[0].mystring;
The value of "W doręczeniu" is not a key, so you cannot use it to get a value. Since your json string is an array you'll have to do json[0].nameto access the first (and only) element in the array, which happens to be the object. Of course, this is assuming json is the variable you store the array into.
var json = [{"type":"spline","name":"W dor\u0119czeniu","color":"rgba(128,179,236,1)","mystring":599}];
console.log(json[0].mystring); //should give you what you want.
EDIT:
To get the last element in a js array, you can simply do this:
console.log( json[json.length -1].mystring ); // same output as the previous example
'length - 1' because js arrays are indexed at 0. There's probably a million and one ways to dynamically get the array element you want, which are out of the scope of this question.

How do I create a Json Object dynamically?

I want to create a Json object from the below string using Java
{"attributes":{"numvcpus":1,"memsize":3072},"id":"OS Node","type":"image"}
If I know that the string will be what it is , I can create a Json object like this
JsonObject jObj = Json.createObjectBuilder()
.add("attributes",Json.createObjectBuilder()
.add("numvcpus",1)
.add("memsize",3072))
.add("id", "OS node")
.add("type": "image").build();
But the problem here is I don't know how many values will come in the nested json object i.e, the json object which is the value for "attributes" field. There may be additional fields like "disksize": 30, "lcpu": 4 etc . Is there any way to dynamically create Json objects, using for loop, while loop ?