splitting string by ],[ and creating json objects - javascript

I am grabbing values from a textarea with document.getElementById("textarea-id").value. I believe this grabs a object of type string.
var b = document.getElementById("textarea-id").value
I will JSON.stringify(b) because I have quotes in b so this will escape the quotes.
var c = JSON.stringy\ify(b)
I want to test if c is actually a JSON object. If it is, put each JSON object in an array. (there might be multiple JSON objects)
To me the easiest way to do so would be to separate the string by the ],[ values that separate the JSON objects. I'm not sure how to separate each object by ],[ while preserving the brackets.
example JSON object:
[{
"a":1,
"b":2
}],
[{
"c":3,
"d":4
}]

Consider ...
c = c.replace("],[", "]###[");
result = c.split("###");
... by using replace, we are changing the , between the ] [ to something unique that you can then split.

Related

JSON array with single element

I am working on a project that has JSON format output. I need a clarity on the JSON array structure. So There are fields that are multiple entry like an array. If an element is an array but has only one value, does it still include an array node '[' in the structure?
Example:
This is a sample JSON element which is an array and has multiple values.
"Talents": [
{
"Items": "test"
},
{
"Items": "test"
}
]
If this element does not have multiple values, will it appear as below?
"Talents":
{
"Items": "test"
}
The '[' does not appear for an array type element with single value. Can someone Pls clarify this?
Single-item arrays will still include the array brackets in JSON format, as they are still arrays. In other words, there is no such native mechanism which converts single-item arrays to a non-array representation. So with your single-item example, it would be represented like this:
"Talents": [
{
"Items": "test"
}
]
You can easily test this out with some simple code:
let jsonSingleItem = { "Talents": [ {"Items": "item1"} ] };
let arraySingleItem = [ {"Items": "item1"} ];
console.log(JSON.stringify(jsonSingleItem));
console.log(jsonSingleItem);
console.log(arraySingleItem);
Which yields the following output:
{"Talents":[{"Items":"item1"}]}
{ Talents: [ { Items: 'item1' } ] }
[ { Items: 'item1' } ]
So in all cases (a stringified JSON object, native JSON, and a javascript array) the single item is still in an array.
Note: It is not uncommon that a consumer of an API will send data (i.e. JSON) in ways which are outside the agreed-upon contract/schema that API defines, and this (sending an object instead of a single-object array when there is just one item) is one example I have seen before. It would be up to the owner/developer of the API as to whether they build in flexibility to handle input which deviates from the API schema.
Square brackets ("[]") denotes JSONArray which in your case can access like
Talents[0]
will return
{
"Items": "test"
}
In second case, curve brackets denotes an JSON object. If you want to access value of items. Than you can by
Talents.Items
OR
Talents["Items"]
will return
"Test"
for complete reference,
JSON Syntax

How to access an attribute from a JSON line saved in a position from an array?

This may be a very simple question but I really can't seem to make it work.
I have several JSON lines and a notes array.
Using notes.push(JSONline) I am saving one JSON line per array position, I assume, so in the following manner:
//notes[1]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}
//notes[2]
{"id":"27","valuee":"134","datee":"2016-04-05T15:15:47.238+0100","id2":53}
//notes[3]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":52}
Here is my problem: I want to print one specific attribute, for example id from one specific JSON line in the array. How can I do this?
When I do console.log(notes) it prints all the JSON lines just as expected. But if I do console.log(notes[1]) it prints the first character of the JSON line in that position, not the whole line.
Similarly console.log(notes[1].id) does not print the id from the first JSON line, in fact it prints 'undefined'.
What am I doing wrong?
Thank you so much.
I'd recommend that you parse all the json when you are pushing to notes, like:
notes.push(JSON.parse(JSONLine))
If you are somehow attached to having json strings in an array instead of objects, which I wouldn't recommend, you could always just parse once you have the jsonLine id
JSON.parse(notes[id]).id
Basically, you want to use JSON.parse for either solution and I'd strongly recommend converting them to objects once at the beginning.
You need to remember that JSON is the string representation of a JS object. JS strings have similar index accessor methods to arrays which is why you can write console.log(notes[0]) and get back the first letter.
JavaScript doesn't allow you to access the string using object notation, however, so console.log(notes[0].id) will not work and the reason you get undefined.
To access the data in the string using this method you need to parse the string to an object first.
var notes = ['{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}'];
var note0 = JSON.parse(notes[0]);
var id = note0.id;
DEMO
This leaves the question of why you have an array of JSON strings. While it's not weird or unusual, it might not be the most optimum solution. Instead you could build an array of objects and then stringify the whole data structure to keep it manageable.
var obj0 = {
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
id2: 51
};
var obj1 = {
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
var arr = [obj0, obj1];
var json = JSON.stringify(arr);
OUTPUT
[
{
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
"id2": 51
},
{
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
]
You can then parse the JSON back to an array and access it like before:
var notes = JSON.parse(json);
notes[0].id // 26
That's because you have {"id": "value"... as a string in your key value pairs. "id" is a string so you can't reference it like a property. 1. use
var notes = JSON.parse(notes);
as mentioned in the comments by The alpha
or remove the quotes try
{id:"26", ...}
that's why notes[i].id is returning undefined

How to stringify an array in Javascript?

I am running the following piece of code:
var arr = [];
arr["aaa"] = {
"xxx" : 1,
"ttt" : 2
};
arr["bbb"] = {
"xxx" : 5,
"qqq" : 6
};
var tmp = JSON.stringify(arr);
alert(tmp);
But the result is []. How does one stringify an array with string keys and object values?
Use
var arr = {};
Arrays should only be used for numerically indexed data, not arbitrary properties. Of course you are able to do it, because they are, in fact, objects. But it won't work in JSON.
Instead, just use objects.
You can't do that, for two reasons:
The stringify method only consider the data in the array, not properties.
There is no JSON format for an array with properties.
If you want the representation of an array in the JSON, you need to put the data in the actual array, not as properties in the array object.
If you want the properties in the JSON, you need to use a plain object instead of an array.

JSON returning multiple columns, but all values as single string. How do I get matching key-value from array?

Here's my problem, I make an ajax call, get a response:
$.getJSON('fpCustom.cfc?method=getSysCounts',function(data){buildChart(data);});
I get a JSON reponse. Raw result:
{"COLUMNS":["ABC","DEF","GHI"],"DATA":[[11,27,4]]}"
When I ask for COLUMN[0], I get correct value: 'ABC', but when I ask for DATA[0], I get the whole DATA string: 11,27,4. I think it probably has to do with the double square bracket, but don't know how to fix that.
How do I get DATA[0], which should be 11?
For the JSON:
{"COLUMNS":["ABC","DEF","GHI"],"DATA":[[11,27,4]]}"
The property DATA is an array of arrays.
Consider it like this: DATA = [a, b, c], where a, b and c are variables. The thing is that your a is another array, just as DATA is.
This way DATA[0], the first element of the DATA array, is an array.
How do I get DATA[0], which should be 11?
The value you want is in: DATA[0][0]:
Because:
DATA[0] -> [11,27,4]
Then:
DATA[0][0] -> 11
DATA[0][1] -> 27
DATA[0][2] -> 4
{"COLUMNS":["ABC","DEF","GHI"],"DATA":[[11,27,4]]}"
In COLUMNS is single dimentional array and DATA is two dimentional array so you have to access value of DATA[i][j]
check example

Javascript: Best way to convert associative array to string and back the other way later?

I have an associative array as follows:
var AssocArray = { id:0, folder:'Next', text:'Apple' };
Now I need to store this in a database, so I figure I would just convert this into a string, store it in the database and then pull it out of the database and put it back into a javascript array later on.
The catch is that the actual # of items, and the array variables will be different every time (hence why I wanted to store it as one long string instead).
What’s the best way to convert this associative array into a string, and then also vice versa, how to convert a string into an associative array?
There is nothing better than JSON for it:
var str = JSON.stringify(obj);
// >> "{"id":0,"folder":"Next","text":"Apple"}"
var obj = JSON.parse(str);
// >> Object({ id: 0, folder: "Next", text: "Apple" })

Categories

Resources