Javascript map CSV string to JSON array - javascript

this one baffles me and I'm not even sure I'm searching the correct keywords for possible explanations.
I am sending an RPC to a remote server. The response I get is just a comma-delimited string with values (no keys) like so:
val1,val2,val3,val4,val5,val6,val7,val8,val9
When I receive this response I need to map these values through JS to keys (hard-coded, I designate) and generate a JSON array like this:
{
"response": {
"mykey1" : "val1",
"mykey2" : "val2",
"mykey3" : "val3",
"mykey4" : "val4",
"mykey5" : "val5",
"mykey6" : "val6",
"mykey7" : "val7",
"mykey8" : "val8",
"mykey9" : "val9"
}
}
Can anybody nudge me in the right direction...sample code or tutorials that are close to what I am looking for? This is a for middleware script that gets called when server receives the response.
This is my first post here, been looking a long time learning and applying in Obj-C and as I am learning Swift, but JS is new to me. I apologize in advance if I am breaking any protocols by asking for help without posting my feeble attempts at figuring this out...

You can split the response on comma, which will give you an array.
Since both arrays (keys and vals) are the same length, you can loop over either and create your array of objects that way. See below
var response = 'val1,val2,val3,val4,val5';
var keys = [
'key1', 'key2', 'key3', 'key4', 'key5'
];
var dict = [];
var vals = response.split(',');
vals.forEach(function(val, i) {
dict[keys[i]] = val;
});
console.log(dict);

Read my comment, then check this out:
var result = 'val1,val2,val3,val4,val5,val6,val7,val8,val9';
// real question should be why result is not JSON already
var resArray = result.split(',');
console.log(resArray[0]); // first result
console.log(resArray[1]); // second result

Related

How to read the values inside the json array

I have a json like
var obj={
"address":{
"addlin1":"",
"addlin2":""
},
"name":"sam",
"score":[{"maths":"ten",
"science":"two",
"pass":false
}]
}
Now when Iam trying to modify the json iam try an array variable and passing above json to that like
var data=JSON.parse(obj);
var json={};
json['name']=data['name'];
json['address']={};
json['address']['addressline1']=data['address']['addlin1'];
json['address']['addressline2']=data['address']['addlin2'];
json['marks']={};
json['maths']=data['score']['maths'];
For name and address I was able to form the json as i was expecting.But for marks I was unable.May be in obj json score values are in [ ]
So,when i console the json it is in this way
"name":"sam",
"address":{
"addresslin1":"",
"addresslin2":""
},
"score":{}
}
So how can I also read the values inside [] array.
Can someone help me
Thanks
json['maths']=data['score'][0]['maths'];
if you're not sure that data['score'] has any elements you can check prior to reading maths key:
if (data['score'].length) {
json['maths']=data['score'][0]['maths'];
}
data['score'] is an array, so you can't read it like that
json['maths']=data['score']['maths'];
you have to read it like that:
json['maths'] = data['score'][0].maths;
Also, obj is not a JSON, but a JavaScript object. You can use it directly.
json['maths'] = obj['score'][0].maths;
A JSON is a string, like that:
JSON.stringify(obj)
var json = "{"address":{"addlin1":"","addlin2":""},"name":"sam","score":[{"maths":"ten","science":"two","pass":false}]}";
create another json2 to contain score data then assign to json.
for example :
var json={};
json2 = {}
json2[0] = 1;
json2[1] = 2;
json[0] = json2;

Counting records in JSON array using javascript and Postman

I have a control that returns 2 records:
{
"value": [
{
"ID": 5,
"Pupil": 1900031265,
"Offer": false,
},
{
"ID": 8,
"Pupil": 1900035302,
"Offer": false,
"OfferDetail": ""
}
]
}
I need to test via Postman, that I have 2 records returned. I've tried various methods I've found here and elsewhere but with no luck. Using the code below fails to return the expected answer.
responseJson = JSON.parse(responseBody);
var list = responseBody.length;
tests["Expected number"] = list === undefined || list.length === 2;
At this point I'm not sure if it's the API I'm testing that's at fault or my coding - I've tried looping through the items returned but that's not working for me either. Could someone advise please - I'm new to javascript so am expecting there to be an obvious cause to my problem but I'm failing to see it. Many thanks.
In postman, under Tests section, do the following (screenshot below):
var body = JSON.parse(responseBody);
tests["Count: " + body.value.length] = true;
Here is what you should see (note: I replaced responseBody with JSON to mock up example above):
Correct your json. and try this.
=======================v
var test = JSON.parse('{"value": [{"ID": 5,"Pupil": 1900031265,"Offer": false},{"ID": 8,"Pupil": 1900035302,"Offer": false,"OfferDetail": ""}] }')
test.value.length; // 2
So you need to identify the array in the json (starting with the [ bracket. and then take the key and then check the length of the key.
Here's the simplest way I figured it out:
pm.expect(Object.keys(pm.response.json()).length).to.eql(18);
No need to customize any of that to your variables. Just copy, paste, and adjust "18" to whatever number you're expecting.
This is what I did for counting the recods
//parsing the Response body to a variable
responseJson = JSON.parse(responseBody);
//Finding the length of the Response Array
var list = responseJson.length;
console.log(list);
tests["Validate service retuns 70 records"] = list === 70;
More updated version of asserting only 2 objects in an array:
pm.test("Only 2 objects in array", function (){
pm.expect(pm.response.json().length).to.eql(2);
});
Your response body is an object you cannot find the length of an object try
var list = responseJson.value.length;
First of all you should convert response to json and find value path. Value is array. You should call to length function to get how many objects in there and check your expected size
pm.test("Validate value count", function () {
pm.expect(pm.response.json().value.length).to.eq(2);
});
I had a similar problem, what I used to test for a certain number of array members is:
responseJson = JSON.parse(responseBody);
tests["Response Body = []"] = responseJson.length === valueYouAreCheckingFor;
To check what values you're getting, print it and check the postman console.
console.log(responseJson.length);
Counting records in JSON array using javascript and insomnia
//response insomnia
const response = await insomnia.send();
//Parse Json
const body = JSON.parse(response.data);
//Print console:
console.log(body.data.records.length);
pm.test("Only 2 objects in array", function (){
var jsonData = pm.response.json();
let event_length = jsonData.data.length;
pm.expect(event_length).to.eql(2);
});
As mentioned in the comments, you should test responseJson.value.length
responseJson = JSON.parse(responseBody);
tests["Expected number"] = typeof responseJson === 'undefined' || responseJson.value.length;
I was facing similar issue while validating the length of an array inside a JSON. The below snippet should help you resolve it-
responseJson = JSON.parse(responseBody);
var list = responseBody.length;
tests["Expected number"] = responseJson.value.length === list;
Working Code
pm.test("Verify the number of records",function()
{
var response = JSON.parse(responseBody);
pm.expect(Object.keys(response.value).length).to.eql(5);
});
//Please change the value in to.eql function as per your requirement
//'value' is the JSON notation name for this example and can change as per your JSON

node red array / how to "use" specific place

in node red i collect values with "Collector" the collector sends me an "Object" with all pairs of values when one of them is updated:
{ "mqtt/1/": "-127.00", "mqtt/0/": "41.94" }
with "json" and after with "stringsplit" i got an array of f.e. 9 values:
array [9] (can be up to 80 pairs of values)!
[ "{", "mqtt/1/", ":", "-127.00", ",", "mqtt/0/", ":", "41.61", "}" ]
now i want to have a function node which compares the Value (-127.00) from the Topic (mqtt/1/) with the Value (41.61) from the Topic (mqtt/0/).
this i working ...BUT only if i know which is the first topic/value and which is the second...
var outputMsgs = msg.payload;
var top1=outputMsgs[1];
var val1=outputMsgs[3];
var top2=outputMsgs[5];
var val2=outputMsgs[7];
msg = {payload: val1}
var msg2 = {payload: val2}
if (val1>val2)
{var msgOUT={payload: "BIGGER"};}
return [msg, msg2, msgOUT];
But the Problem is, that sometimes "mqtt/1/" comes first, sometimes "mqtt/0/" and values will be switched. So now, maybe somebody can help to write a function to pick the right value with the right topic to compare them in the next step.
Maybe is there a Way to look if the topic contains 0, 1 ...80, and then save it in this order in a array???
Thank you in advance!
If the initial msg.payload is truly a javascript object as you describe, ie:
msg.payload = { "mqtt/1/": "-127.00", "mqtt/0/": "41.94" }
then you can reference the two values as:
var value1 = msg.payload["mqtt/1/"];
var value1 = msg.payload["mqtt/2/"];
If msg.payload is actual a JSON string, then pass the message through a JSON node first to convert it to the object.
There is no need to try splitting the string yourself and parsing the content.

Get json data from a file

I wan't to get data from a json file without knowing exacly where the data is:
I have this json
var names= [
{
"category":"category1" ,
"name1":"david",
"name2":"jhon",
"name3":"peter"
},
{
"category":"category2" ,
"name1":"Smith" ,
"name2":"Anna",
}
]
suppose i have a string variable:
var str='category2';
how can i get category2.name1 using the variable?
I don't want to use names[1].name1 because i don't know whats in str and i want to avoid using for loop.
There are some build-in functions that may help you. For example:
var matchingElements = names.filter(function(object, index, array) {
return object.category == str;
});
What you're looking for will always be in matchingElements[0].name1 if matchingElements.length > 0.

JavaScript JSON parse by a given key without looping

Given a JSON string as this:
{
"__ENTITIES": [
{
"__KEY": "196",
"__STAMP": 1,
"ID": 196,
"firstName": "a",
"middleName": "b",
"lastName": "c",
"ContactType": {},
"addressCollection": {
"__deferred": {
"uri": "/rest/Contact(196)/addressCollection?$expand=addressCollection"
}
},
"__ERROR": [
{
"message": "Cannot save related entity of attribute \"ContactType\" for the entity of datastore class \"Contact\"",
"componentSignature": "dbmg",
"errCode": 1537
}
]
}
]
}
Is there a method to get just the __ERROR record, I know I can use
var mydata = json.parse(mydata) and then find it from the mydata object. But I was hoping there was a method to only return the ERROR field something like
json.parse(mydata, "__ERROR") and that gets only the information in the __ERROR field without turning the whole JSON string into an object
"Is there a method to get just the __ERROR record, I know I can use var mydata = json.parse(mydata) ... But I was hoping there was ... something like json.parse(mydata, "__ERROR")"
There may be libraries that do this, but nothing built in. You need to write code that targets the data you want.
The closest you'll get will be to pass a reviver function to JSON.parse.
var errors = [];
var mydata = JSON.parse(mydata, function(key, val) {
if (key === "__ERROR")
errors.push(val);
return val
});
without turning the whole json string into an object
That's hardly possible, you would need some kind of lazy evaluation for that which is not suitable with JS. Also, you would need to write your own parser for that which would be reasonable slower than native JSON.parse.
Is there a method to get just the __ERROR record
Not that I know. Also, this is an unusual task to walk the whole object tree looking for the first property with that name. Better access __ENTITIES[0].__ERROR[0] explicitly.
If such a function existed, it would have to parse the whole thing anyway, to find the key you're looking for.
Just parse it first, then get the key you want:
var mydata = JSON.parse(mydata);
var errorObj = mydata.__ENTITIES[0].__ERROR[0];
If you want, you may create your own function:
function parseAndExtract(json, key) {
var parsed = JSON.parse(json);
return parsed[key];
}

Categories