How to get key "employee "
{
employee":{"name":"John","age":12}
}
It's not about Angular, this is plain Javascript:
const obj = { employee:{name:"John",age:12}}
const key = Object.keys(obj)[0]
You can use forEach to get your output if you use Array Object
function example1(array){
let res = [];
array = [{"ex1":{"name":"John1","age":12}}, {"ex2":{"name":"John2","age":12}}, {"ex3":{"name":"John3","age":12}}]
array.forEach((e, idx) => {
res.push(Object.keys(e))
})
document.getElementById("ex1").innerHTML = JSON.stringify(res);
}
<input type="button" value="example1" onclick="example1()">
<p id="ex1"></p>
if you just use only object you can use For...in to get your output
function example2(array){
let res = [];
obj = {"ex1":{"name":"John1","age":12}, "ex2":{"name":"John2","age":12}, "ex3":{"name":"John3","age":12}}
for(var val in obj){
res.push(val)
}
document.getElementById("ex2").innerHTML = JSON.stringify(res);
}
<input type="button" value="example2" onclick="example2()">
<p id="ex2"></p>
But remember when you put object or array or whatever check its valid or not. In your object is invalid here is the correct format
{"employee":{"name":"John","age":12}}
I'm passing an object using the jQuery $.post method. When it's loaded using the $.get method, I need that the message field of the object is parsed correctly. I was able to remove the equal "=" sign and the "&" sign, but if it's a long message it will contain the plus "+" sign and the commas are not displayed correctly. Here is the console output i get:
{user: "demo", message: "Lorem+ipsum+dolor+sit+amet%2C+consectetur+adipisci…+qui+officia+deserunt+mollit+anim+id+est+laborum."}
message: "Lorem+ipsum+dolor+sit+amet%2C+consectetur+adipiscing+elit%2C+sed+do+eiusmod+tempor+incididunt+ut+labore+et+dolore+magna+aliqua.+Ut+enim+ad+minim+veniam%2C+quis+nostrud+exercitation+ullamco+laboris+nisi+ut+aliquip+ex+ea+commodo+consequat.+Duis+aute+irure+dolor+in+reprehenderit+in+voluptate+velit+esse+cillum+dolore+eu+fugiat+nulla+pariatur.+Excepteur+sint+occaecat+cupidatat+non+proident%2C+sunt+in+culpa+qui+officia+deserunt+mollit+anim+id+est+laborum."
user: "demo"
__proto__: Object
The commas are replaced by the %2C character and the spaces are replaced from the plus sign.
How to obtain the text without this signs?
here is a function I write for this scope, but it's not working at all.
function parseData(data){
var params = {}
params.data = data.split("&");
params.result = {};
for(var i = 0; i < params.data.length; i++) {
var item = params.data[i].split("=");
params.result[item[0]] = item[1];
}
return params.result;
}
Use this one :
function parseData(data){
return decodeURIComponent((data + '').replace(/\+/g, '%20'));
}
Use this function hope it will work for you :
export function parseData(data) {
url = decodeURI(url);
if (typeof url === 'string') {
let params = url.split('?');
let eachParamsArr = params[1].split('&');
let obj = {};
if (eachParamsArr && eachParamsArr.length) {
eachParamsArr.map(param => {
let keyValuePair = param.split('=')
let key = keyValuePair[0];
let value = keyValuePair[1];
obj[key] = value;
})
}
return obj;
}
}
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?
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]);
}
I have this js:
var json = {"products":[{"id":"6066157707315577","reference_prefix":"BB","name":"BeanieBaby","product_line":false,"has_ideas":true},{"id":"6066197229601550","reference_prefix":"BBAGS","name":"BlackBags","product_line":false,"has_ideas":false}],"pagination":{"total_records":4,"total_pages":1,"current_page":1}}
var stuff = json.products.filter(function(obj) {
return obj.has_ideas === true
});
console.log(stuff);
I need help returning a js obj in the same format it started in (var json = {"products":[...) but containing only the filtered objects if they exist. If not, i just want an empty array. How do I do this?
Just create your object and fill in its 'products' property :
var jsonObj = {"products":[{"id":"6066157707315577","reference_prefix":"BB","name":"BeanieBaby","product_line":false,"has_ideas":true},{"id":"6066197229601550","reference_prefix":"BBAGS","name":"BlackBags","product_line":false,"has_ideas":false}],"pagination":{"total_records":4,"total_pages":1,"current_page":1}}
var stuff = {};
stuff.products = jsonObj.products.filter(function(obj) {
return obj.has_ideas === true
});
console.log(stuff);