Javascript get variable into brackets - javascript

I am getting some data from a url which looks like this:
{"654":{"name”:”…etc}
I have this data in a variable called result.
If I do this:
var mydata = [{"654":{"name”:”…etc}];
it works fine but if I do this:
var mydata = [+result+];
or
var mydata = [result];
I get error so my question is how do I get this to work so I can do:
var mydata = [ +mydatahere+ ];
?

It looks like you're receiving that information as a JSON string. If so, you need to parse it:
var data = JSON.parse(result);
Example:
// The JSON string
var result = '{"654":{"name":"foo"}}';
// Parse it
var data = JSON.parse(result);
// Use it
console.log(data[654].name);
// Use it in a loop
var key;
for (key in data) {
console.log(key + " is ", data[key]);
}

Related

Concatenate JSON and Index variables

There is an input field, Which has name metadata.country. The functionality is to get the name and split than make those index in square brackets ['metadata']['country']. I want to concatenate JSON and Index variables to get the country.The issue is when I try to join, it return [object Object].
Code:
//Input Fields (Html)
<input id="dataX" name="metadata.country">
<input id="dataY" name="metadata.city">
//Get ID
var inputField_Name = document.getElementById("dataX").attr['name'];
//JSON Data
var json = {name:"John",metadata:{country:"USA",city:"newyork"}};
//Split by dot
var targetName = inputField_Name.split('.');
//Convert them into square brackets
let copy='';
targetName.map(function(key, index) {
copy +="['"+key+"']";
});
//Response copy: ['metadata']['country']
console.log(json + copy);
//Response: [object Object]['metadata']['country']
Expected Response:
"USA"
//Don't want this method:
json [1];
Below snippet will help you find out the data from the object. Hope this helps
var inputField_Name = "metadata.country"
var json = {name:"John",metadata:{country:"USA"}};
var targetName = inputField_Name.split('.');
let copy='';
const data = targetName.reduce((result, targetKey) => result[targetKey] || {}, json)
console.log(data)
Below method can be used to update the value at the specified location without mutating the original object. you can get the data from the method and can use it to do setState.
let updateValue = (dataObj, keys, updatedValue) => {
let json = JSON.parse(JSON.stringify(dataObj));
let result = (keys ||[]).reduce((result, targetKey, index) => {
if(index === targetName.length - 1){
result[targetKey] = updatedValue;
return result[targetKey]
}
return result[targetKey] || {}
}, json)
return json;
}
var inputField_Name = "metadata.country"
var json = {name:"John",metadata:{country:"USA"}};
var targetName = inputField_Name.split('.');
const updatedJsonObj = updateValue(json, targetName, "CANADA")
console.group("Updated JSON");
console.log(updatedJsonObj)
console.groupEnd()
console.group("Original JSON");
console.log(json)
console.groupEnd()
You can try
JSON.stringify(json) + JSON.stringify(index)
var json = {name:"John",country:"USA"};
var index= ['1'];
console.log(JSON.stringify(json) + JSON.stringify(index));
You don't need to map through you can directly get the value from the object.
let inputField_Name = "metadata.country"
let json = {name:"John",metadata:{country:"USA"}};
let [meta, key] = inputField_Name.split('.');
let out= json[meta][key];
console.log(out)

How to retrieve JSON keys without any buffer error?

Below is my JSON that I get from reading a text file using node js readFileSync.
{"MESSAGE":"Triggered for ID 453289","STATUS":"02","APPROVAL_COMPLETED":""}
Now when I try to get the keys of the JSON using the code below
Object.keys(json);
I ge the below error
The keys are 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114
Also if I try to get the value of the JSON element like below
json["STATUS"]; // I also used json.status (neither works)
I get the value as undefined.
Below is the entire code
var fs = $.require('fs');
var stream = fs.readFileSync('api.txt', 'utf8');
console.log("Global " +JSON.stringify(stream));
var data = JSON.parse(stream);
var retrievedData = JSON.stringify(data.retrievedData);
var json = JSON.parse(retrievedData);
console.log("The API Output is " +json);
var keys = Object.keys(json);
console.log("The keys are "+keys);
var flag = json["STATUS"];
//var retrievedData = stream.retrievedData;
console.log("flag is "+flag);
Below are the particulars
Output of Data is
{"retrievedData":"{\"MESSAGE\":\"Triggered for Group ID 453289\",\"STATUS\":\"02\",\"APPROVAL_COMPLETED\":\"\"}","statusCode":200,"MESSAGE":"API successfully called"}
Output of retrievedData is
{"MESSAGE":"Triggered for ID 453289","STATUS":"02","APPROVAL_COMPLETED":""}
Please help in resolving the issues.
The problem is that your data is a string, so you need to parse it into an object:
let input = '{"MESSAGE":"Triggered for ID 453289","STATUS":"02","APPROVAL_COMPLETED":""}'
console.log(Object.keys(input));
let parsed = JSON.parse(input);
console.log(Object.keys(parsed));
console.log(parsed['STATUS']);
The error in your code is calling var retrievedData = JSON.stringify(data.retrievedData); - the data appears to already a string at that point, so you double encode it. You can just skip the JSON.stringify and it would work:
var stream = `{
"retrievedData": "{\\"MESSAGE\\":\\"Triggered for ID 453289\\",\\"STATUS\\":\\"02\\",\\"APPROVAL_COMPLETED\\":\\"\\"}"
}`
var data = JSON.parse(stream);
var retrievedData = data.retrievedData;
var json = JSON.parse(retrievedData);
console.log("The API Output is " +json);
var keys = Object.keys(json);
console.log("The keys are "+keys);
var flag = json["STATUS"];
Dont stringify the JSON when passing it as a parameter to Object.keys().
var keys = Object.keys(json);
Instead of
var keys = Object.keys(JSON.stringify(json));
You can directly apply a loop on retrievedData to find keys:-
for(var temp in retrievedData)
{
console.log(temp)
}
Here temp will be your keys
Try and change
var keys = Object.keys(JSON.stringify(json));
towards
var keys = Object.keys(json);
Does that help to resolve your issue?

how to parse a json data with multiple values?

i have a multidimensional json . i want to parse it to get the values.
var json='{"Links":[],"RequestedObject":{"FieldContents":{"21514":{"Type":1,"IsError":false,"Value":"Saneen","FieldId":21514,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21516":{"Type":1,"IsError":false,"Value":"English","FieldId":21516,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21517":{"Type":1,"IsError":false,"Value":"Malayalam","FieldId":21517,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21515":{"Type":2,"IsError":false,"Value":26.0,"FieldId":21515,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21518":{"Type":2,"IsError":false,"Value":80.0,"FieldId":21518,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21519":{"Type":2,"IsError":false,"Value":40.0,"FieldId":21519,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21520":{"Type":4,"IsError":false,"Value":{"ValuesListIds":[72639],"OtherText":null},"FieldId":21520,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21523":{"Type":3,"IsError":false,"Value":"2017-03-29T00:00:00","FieldId":21523,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21510":{"Type":6,"FieldId":21510,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21511":{"Type":21,"FieldId":21511,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21512":{"Type":22,"FieldId":21512,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21521":{"Type":11,"Value":null,"FieldId":21521,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}}}},"IsSuccessful":true,"ValidationMessages":[]}';
i have tried with JSON.parse , but no luck.
Here is an simple example of JSON.parse() and here is document for that:
var json='{"Links":[],"RequestedObject":{"FieldContents":{"21514":{"Type":1,"IsError":false,"Value":"Saneen","FieldId":21514,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21516":{"Type":1,"IsError":false,"Value":"English","FieldId":21516,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21517":{"Type":1,"IsError":false,"Value":"Malayalam","FieldId":21517,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21515":{"Type":2,"IsError":false,"Value":26.0,"FieldId":21515,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21518":{"Type":2,"IsError":false,"Value":80.0,"FieldId":21518,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21519":{"Type":2,"IsError":false,"Value":40.0,"FieldId":21519,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21520":{"Type":4,"IsError":false,"Value":{"ValuesListIds":[72639],"OtherText":null},"FieldId":21520,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21523":{"Type":3,"IsError":false,"Value":"2017-03-29T00:00:00","FieldId":21523,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21510":{"Type":6,"FieldId":21510,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21511":{"Type":21,"FieldId":21511,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21512":{"Type":22,"FieldId":21512,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21521":{"Type":11,"Value":null,"FieldId":21521,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}}}},"IsSuccessful":true,"ValidationMessages":[]}';
var obj = JSON.parse(json);
console.log(obj);
// retrieve particular fields
var newFieldContents = {};
for(var key in obj['RequestedObject']['FieldContents']){
var o = obj['RequestedObject']['FieldContents'][key];
newFieldContents[key] = {
Value: o['Value'],
FieldId: o['FieldId']
}
}
console.log(newFieldContents);
Update
Add how to retrieve particular fields.

Get the Inner Array Value of JSON in Javascript

I need the basic Help , I have a json object in the following format
Data = {"line":"1",
"column":"1"
"response":[{"criteria":"starts","response":"358","field":"S"},
{"criteria":"ends","response":"359","field":"H"}]}
I can get the Line and Column value as below
var obj = $.parseJSON(data);
var line = obj['line'];
var column=obj['column'];
I have tried below format but i cannt get response value:
var res = new Array(obj['response']);
alert(res[0]['criteria']);
And
var jsonObject = $.parseJSON(obj['response']);
var innerArray = jsonObject['response'];
alert(innerArray[0].fieldvalue);
how can i get the values in obj['response'] ? Any one could help me to find the solution
Why do you need to create a new array?
var res = new Array(obj['response']);
alert(res[0]['criteria']);
It is already converted to an array after you parse the JSON string, so this will work:
var res = obj['response'];
alert(res[0]['criteria']);

building a JSON string

I have a two part question (Very new to JSON)
I need to build a json object out of attr 'data-id'. Can a JSON object be a single 'array' of numbers?
I have got the code for this but I am struggling to build the JSON object, as follows:
code:
var displayed = {};
$('table#livefeed tr').each(function (i) {
var peopleID = $(this).attr("data-id");
//console.log("id: " + peopleID);
if(peopleID!="undefined") displayed += peopleID;
});
console.log(displayed);
However this does not work properly, I just end up with string of objects added together.
A JSON object can be an array of numbers.
Try something like this:
var displayed = [];
$('table#livefeed tr').each(function (i) {
var peopleID = $(this).attr("data-id");
if(peopleID!="undefined")
displayed.push(peopleID);
});
console.log(displayed);
To turn it into JSON,
JSON.stringify(displayed);
First you build and object then you use JSON.stringify(object); to create the string. But you also have an error. If you are checking peopleID to be defined you need to use typeof as an undefined attribute won't be the string 'undefined':
var displayed = [];
$('table#livefeed tr').each(function (i) {
var peopleID = $(this).attr("data-id");
//console.log("id: " + peopleID);
if(typeof(peopleID)!="undefined") displayed.push(peopleID);
});
console.log(displayed);
var jsonDisplay = JSON.stringify(displayed);
console.log("JSON: " + jsonDisplay);

Categories