it this expression possible in js? - javascript

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"]]}

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

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

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

Building an object in javascript returns error

I am building an array as an object, which a function I'm writing will eventually crawl. It's static data, so once it's populated nothing is likely to be added or removed, but I'm having difficulty formatting it properly.
The variable declaration works great if I have only one record's worth of data:
var panel = {
'url':'http://www.minorworksoflydgate.net/Testament/Clopton/nw_test_1.html',
'x':[1.63, 3.53],
'y':[6.58, 7.26],
'z':[2.05, 2.81]
}
However, if I try to add a second record's worth of information:
var panel = {'0':['url':'http://www.minorworksoflydgate.net/Testament/Clopton/sw_test_1.html',
'x':[-9.38, -7.47],
'y':[6.80, 7.49],
'z':[-8.18, -8.85]],'1':[
'url':'http://www.minorworksoflydgate.net/Testament/Clopton/nw_test_1.html',
'x':[1.63, 3.53],
'y':[6.58, 7.26],
'z':[2.05, 2.81]}
}
I get the following error: SyntaxError: Unexpected token ':'. Expected either a closing ']' or a ',' following an array element. I've tried every combination I can think of: wrapping each hunk of data in braces or square brackets and both explicitly declaring the keys and not declaring the keys. It all results in variations of this error. Where am I messing up in terms of formatting this information?
Your combining object literals and arrays in a weird way. Here is probably what you are looking for
[
{
'0':....
},
{
'1':...
}
]
This is an array of objects, where the objects can be your data records.
What I see in the code that is the problem is
[ '0': '.....'] //illegal
Square brackets represent arrays, which is a list of data whether they are strings, numbers, or objects.
[ '0', {}, 'blah', 1.2] //legal
Curly brace is the object literal or associative arrays.
{ '0': '...' }
EDITED
People say that arrays are object literals because they behave like one at run-time. You are defining array and object literals, so there are specific rules that come into play. In your code, if you instead wrote
var panel = [];
var index1 = []
panel['0'] = index1
index1['url'] = 'http://';
index1['x'] = 1.2;
var index2 = [];
index2['url'] = 'http://';
This would work, but as you can see it is a little convoluted. When you are writing an array literal, it is a list of comma separated values, and not associated keys. If you want associated keys, use curly brace.
If you want more info, search for JSON data format.

How do I add one single value to a JSON array?

I am kind of new to the world of interface, and i found JSON is amazing, so simple and easy to use.
But using JS to handle it is pain !, there is no simple and direct way to push a value, check if it exists, search, .... nothing !
and i cannot simply add a one single value to the json array, i have this :
loadedRecords = {}
i want to do this :
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
Why this is so hard ???!!!
Because that's an object, not an array.
You want this:
var = loadedRecords = []
loadedRecords.push('1234');
Now to your points about JSON in JS:
there is no simple and direct way to push a value
JSON is a data exchange format, if you are changing the data, then you will be dealing with native JS objects and arrays. And native JS objects have all kinds of ways to push values and manipulate themeselves.
check if it exists
This is easy. if (data.someKey) { doStuff() } will check for existence of a key.
search
Again JSON decodes to arrays and objects, so you can walk the tree and find things like you could with any data structure.
nothing
Everything. JSON just translates into native data structures for whatever language you are using. At the end of the day you have objects (or hashes/disctionaries), and arrays which hold numbers strings and booleans. This simplicity is why JSON is awesome. The "features" you seek are not part of JSON. They are part of the language you are using to parse JSON.
Well .push is an array function.
You can add an array to ur object if you want:
loadedRecords = { recs: [] };
loadedRecords.recs.push('654654');
loadedRecords.recs.push('11');
loadedRecords.recs.push('3333');
Which will result in:
loadedRecords = { recs: ['654654', '11', '3333'] };
{} is not an array is an object literal, use loadedRecords = []; instead.
If you want to push to an array, you need to create an array, not an object. Try:
loadedRecords = [] //note... square brackets
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
You can only push things on to an array, not a JSON object. Arrays are enclosed in square brackets:
var test = ['i','am','an','array'];
What you want to do is add new items to the object using setters:
var test = { };
test.sample = 'asdf';
test.value = 1245;
Now if you use a tool like FireBug to inspect this object, you can see it looks like:
test {
sample = 'asdf,
value = 1245
}
Simple way to push variable in JS for JSON format
var city="Mangalore";
var username="somename"
var dataVar = {"user": 0,
"location": {
"state": "Karnataka",
"country": "India",
},
}
if (city) {
dataVar['location']['city'] = city;
}
if (username) {
dataVar['username'] = username;
}
Whats wrong with:
var loadedRecords = [ '654654', '11', '333' ];

Categories

Resources