how to assign a javascript variable with ndjson value - javascript

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

Related

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 do I extract specific values from the JSON response in Postman using a test?

I need to be able to parse through the JSON results from a Postman response to just pull out the name value in the console output. My JSON looks like this:
"total_count": 7,
"entries": [
{
"type": "collaboration",
"id": "21829111111",
"created_by": null,
"created_at": "2020-03-24T05:37:09-07:00",
"modified_at": "2020-03-24T05:37:09-07:00",
"expires_at": null,
"status": "accepted",
"accessible_by": {
"type": "group",
"id": "3085402",
"name": "Test",
"group_type": "managed_group"
Most of the examples I find are using extracted value to create a variable but I really just need a simple list I can copy and paste.
I've used this code to do something similar but I am not sure how to modify it for us with this data:
var response = JSON.parse(responseBody);
var usernames = response.map(function(account){
    return account.credentials.userName;
});
console.log(usernames);
Any help is appreciated.
Let's walk through it:
var response = JSON.parse(responseBody);
JSON.parse() is taking the JSON response in as a string, and converting it to a JS object, which will then be stored in response.
response.map(...)
The map() function is called on an array and takes a function as a parameter. It calls the function you provide it once for each element in the array that it's called on.
For your particular case, we'll need to modify this a little, since response is an object, rather than an array, and the value you're after, name, is nested in the entries array inside of response. To account for this, we're going to call map() directly on the nested array, and set it equal to a new variable to store the result, like this:
var names = response.entries.map(...);
Now, we can pass map() a function that will extract the name from each element in the entries array. Our function needs to accept the array element as a parameter, and return the extracted name so that map() can add it to the new array it's making.
function(entry) {
return entry.accessible_by.name;
}
In the end, we end up with this:
var response = JSON.parse(responseBody);
var names = response.entries.map(function(entry) {
return entry.accessible_by.name;
});
console.log(names);
This will output an array of names to your browser console. ["Test", ...]
Bonus:
With a little JavaScript syntactic sugar (specifically arrow functions), we can make the function code a little cleaner:
var response = JSON.parse(responseBody);
var names = reponse.entries.map(entry => entry.accessible_by.name);
console.log(names);

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