JSON array with single element - javascript

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

Related

Create Json with specific structure from two different arrays in javascript

I've already tried to find a solution on stack, but I didn't found a possible reply, so I decided to open a topic to ask:
Let's say we have 2 arrays: one containing "keys" and another one containing "values"
Example:
keys = [CO2, Blood, General, AnotherKey, ... ]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[... [
I have to create a Json with a specific structure like:
[{
name: 'CO2',
data: [2,5,4,6]
}, {
name: 'Blood',
data: [4,5,6]
}, {
name: 'General',
data: [1,3,34.5,43.4]
}, {
...
},
}]
I've tried to make some test bymyself, like concatenate strings and then encode it as json, but I don't think is the correct path to follow and a good implementation of it ... I've also take a look on JSON.PARSE, JSON.stringify, but I never arrived at good solution so... I am asking if someone know the correct way to implements it!
EDIT:
In reality, i didn't find a solution since "name" and "data" are no strings but object
Here's one way to get your desired output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = keys.map((x, i) => {
return {"name": x, "data": values[i]}
})
console.log(output)
However, since you're literally constructing key/value pairs, you should consider whether an object might be a better data format to output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = {}
for (let i=0; i<keys.length; i++) {
output[keys[i]] = values[i]
}
console.log(output)
With this data structure you can easily get the data for any keyword (e.g. output.CO2). With your array structure you would need to iterate over the array every time you wanted to find something in it.
(Note: The reason you weren't getting anywhere useful by searching for JSON methods is that nothing in your question has anything to do with JSON; you're just trying to transform some data from one format to another. JSON is a string representation of a data object.)

it this expression possible in js?

I have object data. in data, we have created the following array:
data = {items: [{ "4","5","6" }, {"7","8","9","10","11","12","13","14","15","16"}]}
console.log("items:", items[0]);
but when use in js I get the error
Unexpected token ','
so can I use that code as an object?
This is not a valid javascript object. Objects in javascript are made up of key-value pairs, which is not the case here. The error is occurring here:
data = {items: [{ "4","5","6" }, {"7","8","9","10","11","12","13","14","15","16"}]}
^
The interpreter is expecting a colon : character whereas you give a comma. You may want to use an array instead.
Furthermore, you need to access the items array via data.items rather than items directly:
data = {items: [[ "4","5","6" ], ["7","8","9","10","11","12","13","14","15","16"]]}
console.log("items:", data.items[0]);
This is a syntax issue. In the list of items you have elements like { "4","5","6" }, but this is not the correct syntax. For a list of items you want to put them between [] symbols; {} symbols are used for objects.
With that in mind, this is probably what you are trying to create:
data = {items: [[ "4","5","6" ], ["7","8","9","10","11","12","13","14","15","16"]]}

how to assign a javascript variable with ndjson value

I want to assign the data inside a ndjson file into a js variable. I have tried putting it in an array and an object but that is throwing me error.
I have tried like this ...
var data = [{"attributes":{}}
{"attributes":{}}
{"attributes":{}}]
and
var data = {{"attributes":{}}
{"attributes":{}}
{"attributes":{}}}
But this is not working.
Can someone help me on how to assign this ndjson value to a js variable without throwing error.
ndjson is useful for streaming values — the format
is essentially an array of objects, but (1) the outermost brackets [] are omitted so the array is implied, and (2) the separator between records is a newline instead of a comma. Basically a stream of lines where each line is a record in JSON format. The spec is not clear if a record/line can itself be an array, but objects can contain arrays.
Using the example presented in the spec, you must have received this stream of text in some way:
{"some":"thing"}
{"foo":17,"bar":false,"quux":true}
{"may":{"include":"nested","objects":["and","arrays"]}}
Let's say you've received this and stored it in a variable, which would be a string, input. You could then break this string on newlines with input.split('\n')
parse each one via JSON.parse(…) and save the result in an array.
let input = '{"some":"thing"}\n{"foo":17,"bar":false,"quux":true}\n{"may":{"include":"nested","objects":["and","arrays"]}}';
let result = input.split('\n').map(s => JSON.parse(s));
console.log('The resulting array of items:');
console.log(result);
console.log('Each item at a time:');
for (o of result) {
console.log("item:", o);
}
Javascript array of the object will be like this, see the comma , between them,
var data = [{
"attributes": {}
},{
"attributes": {}
},{
"attributes": {}
}];
console.log(data);
OR objects inside object can be like this and I guess you don't want this,
var data = {
"attributes": {},
"attributes": {},
"attributes": {}
};
console.log(data);

make mongoDB replace single value array with string

I'm very new to mongoDB and am trying to insert an object to the database. (Wow, much more fun than mySQL...). I'm using strongloop's loopback framework and its mongoDB connector.
The object is a xml2js parsed xml message I receive, after parsing and inserting to mongo it looks like this:
{
"_id": ObjectID("55c61ee9391da88435c5753f"),
"offerChange": [
{
"foo": [
"bar"
],
"baz": [
"foo"
]
}
]
}
as you can see, all the key's values are arrays, though all of them contain only one value. Obviously I can convert them to strings before the insert or during xml parsing, but that would require looping over all the object's keys or more work for the worker in the first place, which I'd like to avoid. The real object is much bigger than above shown.
Is there a way to tell mongoDB to automatically convert arrays that have only one value to a string before or after the document gets created?
You need not loop through and convert from array to string in application/database. xml2js provide a neat way to return string if there is only one item and array if there are more items.
explicitArray (default: true): Always put child nodes in an array if
true; otherwise an array is created only if there is more than one.
Initiate your parser as follows
parseString(xml, {explicitArray: false}, function (err, result) {
});

Javascript multi-dimensional array to and from JSON (jQuery?)

I have a Javascript problem where I need to be able to store data like follows:
MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..)
The main array has 10 sub arrays, these sub arrays then contain any number of JavaScript Objects.
I need an efficient way of storing the data this way and need to know how to parse to JSON/decode back to a manageable structure in Javascript.
The reason for this structure is because the Java program I'm communicating with uses this structure.
I'm able to use jQuery if that makes any difference.
Your structure appears to look like this
var myVariable = [
[
{ }, { }, { }
],
[
{ }, { }, { }
]
]
This can be JSON stringified. It yields "[[{},{},{}],[{},{},{}]]"
Use JSON.stringify and JSON.parse, respectively.

Categories

Resources