Get value of json string - json

[
{
"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.

Related

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 length/size of json data

I have use the following codes to get my json data with certain nodes.
console.log(Object.keys(data.Top["person"]).length);
It is work fine in following structure of json data array:
data:{"Top":{"person":[{"A":"a","B":"b"},{"A":"a","B":"b"}]}}
However when the person only have one nodes, it always show the answer 2 to me, it should be answer 1.
data:{"Top":{"person":{"A":"a","B":"b"}}}
Is it possible to solve this error?
length property is supported by type array.
data:{"Top":{"person":[{"A":"a","B":"b"},{"A":"a","B":"b"}]}} in case of this person is array enclosed with [ ]
Where as for data:{"Top":{"person":{"A":"a","B":"b"}}} person is just an object. Hence length is undefined for it.
If you are creating json out of string or formatting it make sure to include [ and ] for person attribute.
JSFiddle
https://jsfiddle.net/d6pqnckh/
Also use JSON formatter to test JSON structure.
UPDATE
Since you are not sure of JSON structure. What you could do is before accessing length of person check if it is an array or object.
if(Object.prototype.toString.call(data.Top.person) === '[object Array]')
alert(data.Top.person.length);
//It is an array
else
alert("I AM OBJECT"); //It is of an object type
Updated Fiddle: https://jsfiddle.net/wys7awuz/
To make it an array regardless https://jsfiddle.net/ofkboh6k/
var p = data.Top.person;
delete data.Top.person;
data.Top.person = [];
data.Top.person.push(p);
alert(data.Top.person.length);
Include this in else part of condition. It will make it an array.
length works for type array.
change your JSON to
data:{"Top":{"person":[{"A":"a","B":"b"}]}}

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);

Create nested JSON structure with Coldfusion

I've been converting CF structs etc to JSON for a while now, and all good. Coldbox in particular makes this really easy.
However, I am currently working with a jQuery Datatable and need to pass it jSON in the format below.
I am starting with an array of objects.
I only want certain properties in each object to go into the final JSON String.
I'm running around in circles and possibly totally overcomplicating converting my data into this format JSON. Can anyone help, or suggest an easy way I might be able to do this..
Also worth mentioning I am building this in coldbox. Coldfusion 9.
{ "aaData": [ [ "Test1", "test#test1", "444444444", "<i class=''icon-pencil icon-large'' data-id=''s1''></i>" ],[ "Test2", "test#test2", "555555555", "<i class=''icon-pencil icon-large'' data-id=''s2''></i>" ],[ "Test3", "test#test3", "666666666", "<i class=''icon-pencil icon-large'' data-id=''s3''></i>" ] ]}
Many Thanks!
======================================================
Here is the code that game we what I needed:
var dataStruct = structNew();
var dataArray = arrayNew(1);
var subsArray = arrayNew(1);
var subs = prc.org.getSubscribers();
for (i=1; i<=arrayLen(subs); i++){
arrayAppend(subsArray,"#subs[i].getName()#");
arrayAppend(subsArray,"#subs[i].getEmail()#");
arrayAppend(subsArray,"#subs[i].getMobile()#");
arrayAppend(subsArray,"<i class='icon-pencil icon-large' data-id='s#subs[i].getID()#'></i>");
arrayAppend(dataArray,subsArray);
arrayClear(subsArray);
};
structInsert(dataStruct,'aaData',dataArray);
event.renderData('json',dataStruct);
OK, so you've got an array which has objects, and the objects contain all the properties which you need to end up in this JSONed array, yeah?
So do this:
create a new array
loop over the array of objects
create a struct
put all the values from each object you need to go into the JSON; be mindful to use associative array notation when setting the keys, to perserve the case of the keys
append the struct to the new array
/loop
serializeJson the new array
I don't think there's any simpler way of doing it.

json file manipulation with javascript

I am getting json as response from server like below;
{"data":"<div align=\"left\"><select id =\"test\"><option id=\"1\" value=\"one\"><option id=\"2\" value=\"two\" selected></select></div>"};
I want to manipulate above json file using javascript to change option one to be selected instead of option two.
Any hints please.
Regards,
Raj
Your life would be easier if your JSON was actually data represented as JSON, instead of serialized DOM fragments embedded in a JSON value, e.g.,
[
{"value": "one"}
, {"value": "two", "selected": true}
]
Then when you turn that into an object, you could just do something like this (assume for the sake of the example that you named the result myArray):
myArray[0].selected = true; // Select the first element
myArray[1].selected = false; // Deselect the other element; in many cases, you'd probably need some sort of loop.