Need to remove key(s) from a json array under javascript (jquery).
Looks like my code is wong although it was working in my Chrome console.
Your help is the most welcome.
Jacques
function test() {
var json = {
"ID": "2196",
"VERSION": "1-2022",
"FILE": "2196.docx"
};
json = JSON.stringify(json)
console.log("json " + json);
delete json['FILE'];
console.log("json " + json);
return;
}
test();
JSON.stringify has an often overlooked parameter called the replacer. It can accept an array of key names to include in the json output:
JSON.stringify(data, ["ID","VERSION"], " "); // FILE is excluded
Snippet
Run the snippet to see the output with and without using the replacer.
let data = {
"ID": "2196",
"VERSION": "1-2022",
"FILE": "2196.docx"
};
console.log("Without replacer: ",
JSON.stringify(data, null, " ")
);
console.log("Using replacer: ",
JSON.stringify(data, ["ID","VERSION"], " ")
);
You should not stringify the object before removing the key.
function test() {
var json = {
"ID": "2196",
"VERSION": "1-2022",
"FILE": "2196.docx"
};
// stringify to show in console as string
json = JSON.stringify(json)
console.log("json " + json);
// convert back to object so you can remove the key
json = JSON.parse(json);
delete json['FILE'];
// stringify to show new object in console as string
json = JSON.stringify(json);
console.log("json " + json);
return;
}
test();
Related
All
I am trying to convert nested JSON into CSV with object key as group identifier in csv.
this is the JSON I am working on
"Name": "Name",
"LoyaltyNumber": "Loyalty Number",
"LoyaltySaved": "Loyalty Items Were Saved",
"LoyaltyDeleted": "Loyalty Item Was Deleted",
"Add": "Add ",
"Loyalty": " Loyalty",
"DeleteLoyalty": "Delete Loyalty"
},
"LoyaltyViewer": {
"AirlineLoyalty": "Airline Loyalty",
"HotelLoyalty": "Hotel Loyalty",
"CarLoyalty": "Car Loyalty",
"RailLoyalty": "Rail Loyalty"
},
my current script for conversion is
function toCSV(json) {
json = Object.values(json);
let csv = '';
const keys = (json[0] && Object.keys(json[0])) || [];
csv += keys.join(',') + '\n';
for (let line of json) {
csv += keys.map((key) => line[key]).join(',') + '\n';
}
FileSystem.writeFileSync('./destination3.csv', csv);
return csv;
}
but the result is not what is expected result should be similar to this
expected
but i am getting it like this
result
Can you please point me in a right direction , Thanks
you can use papa parse this one is a very powerful tool to handle csv and json data
https://www.papaparse.com/docs#json-to-csv
it has npm and cdn both.
<string xmlns="http://tempuri.org/">
"Result": "Sucess",
"MotorList": [
{
"id": "1",
"titleen": "Camry",
"titlear": "Multi_service"}]
</string>
this XML contain json , so how to parse json data from xml using javascript
From my understanding you result from ajax is not a complete JSON Object.
JSON Object starts with a
{
and ends with
}
Eg:
{
"Result": "Sucess",
"MotorList": [
{
"id": "1",
"titleen": "Camry",
"titlear": "Multi_service"
}
]
}
SO you need to wrap your response within {} and use JSON.parse() to parses to object
Eg:
let response = '"Result": "Sucess", "MotorList": [ { "id": "1", "titleen": "Camry", "titlear": "Multi_service"}]'
let json = JSON.parse("{"+response +"}")
Now you can access your JSON Object like
json.Result
In the provided response only the "MotorList" value contains valid JSON. If you can modify the service then change the response to JSON, it would be the ideal solution. But if you cannot modify the service then you have to parse it using an XML reader and do a series of string operation to get the desired value.
For example the below code extracts the "MotorList" value into JSON:
var parser, xmlDoc;
//Get the value from Ajax
var text = '<string xmlns="http://tempuri.org/">' +
'"Result": "Sucess",' +
'"MotorList": [' +
'{' +
'"id": "1",' +
'"titleen": "Camry",' +
'"titlear": "Multi_service"}]' +
'</string>';
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
//document.getElementById("demo").innerHTML =
var resultString = xmlDoc.getElementsByTagName("string")[0].childNodes[0].nodeValue;
var resultTokens = resultString.substring(resultString.indexOf(',') + 1, resultString.length)
var resultObj = JSON.parse(resultTokens.substring(resultTokens.indexOf(':') + 1, resultTokens.length))
var motorList = resultObj[0]
How read of Object.keys() value JSON ?
I trying read value key name, but give error:
Keys dynamic
{
"marka1": {
"name": "Mika",
},
"beti1": {
"name": "Yii",
}
}
var ojson = JSON.parse(objectJson);
var keys = Object.keys(ojson); //read good key
console.log("test - " + ojson.keys[0].name); //give error
Change it to console.log("test - " + ojson[ keys[0] ].name); because keys[0] is just a string.
I'm using an object as a map and storing objects in it using the pattern map[obj.href] = obj
I'm expecting duplicate keys, but something really weird is happening:
I have 2 completely different (every field) objects stored with different keys, but when a 3rd object has the same key as 1st, a lookup is returning the 2nd object (stored with a different key), and when I do a lookup of the returned object's href, I get that same object again, as if the 2 keys are equivalent.
According to Which characters are valid/invalid in a JSON key name? and some other posts on SO, any valid string can be a key in an object, and you don't need to escape any characters, which I was worried about because of all the '/'s and '#'s.
I'm sureit's just a simple bug in my code, which I can't see it because it's 8 am and I have been up all night. Any help spotting it would be appreciated.
function parseSpellsList($)
{
var spellsList = {};
$("ul[class|='link'],ul[class$='level']").each(function() {
var obj, spell_type, links, i, link, a, span, prevObj, hashKey;
obj = {};
links = this.children;
for (i=0; i<links.length; i++) {
link = links[i];
a = link.children[0];
obj.href = a.href.replace("file:///home/ckot/rpg_app/", "").replace("scripts/", "");
obj.name = a.innerHTML.replace("<b>", "").replace("</b>", "");
hashKey = obj.href;
prevObj = null;
if ( !(spellsList.hasOwnProperty(hashKey))) {
// debug code
if ("Blood Blaze" === obj.name || "Vomit Swarm" === obj.name) {
console.log("storing " + JSON.stringify(obj, null, " ") + " with hashKey: " + hashKey);
}
spellsList[hashKey] = obj;
} else {
console.log("\nWARNING: hashKey " + hashKey + " already exists");
prevObj = spellsList[hashKey];
console.log("object we which to store with hashKey: " + hashKey + "\n" + JSON.stringify(obj, null, " ")) ;
console.log("object retrieved with hashKey: " + hashKey + "\n" + JSON.stringify(prevObj, null, " "));
console.log("object retrieved with hashKey: " + prevObj.href + "\n" + JSON.stringify(spellsList[prevObj.href], null, " ") + "\n");
}
}
});
}
when I run it I get the following output:
storing {
"href": "advancedRaceGuide/featuredRaces/orcs.html#blood-blaze",
"name": "Blood Blaze"
} with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
storing {
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
} with hashKey: advanced/spells/vomitSwarm.html#vomit-swarm
WARNING: hashKey advancedRaceGuide/featuredRaces/orcs.html#blood-blaze already exists
object we which to store with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
{
"href": "advancedRaceGuide/featuredRaces/orcs.html#blood-blaze",
"name": "Blood Blaze"
}
object retrieved with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
{
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
}
object retrieved with hashKey: advanced/spells/vomitSwarm.html#vomit-swarm
{
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
}
EDIT:
just for some context I'm using:
node v0.10.22
npm v1.4.24
and the npm modules:
jsdom v1.0.0-pre.3
jquery v2.1.1",
nvm, I was initializing obj at the start of $.each() instead of inside the nested for loop. :(
i guess I just need to get some sleep.
I am having the following code:
data = JSON.stringify({
"result": [
{
"username": "username should not empty"
},
{
"password": "password should not empty"
}
],
"validate_flag": 1
})
data = JSON.parse(data);
$.each(data,function(index,value){
console.log(index);
console.log(value);
});
console.log(data);
Here I can extract the second key "validate_flag" directly using $.each. But when I tried to extract "result" I got two objects. Now,how can I effectively use $.each() to extract the following json regardless of multi-dimensional or single-dimensional. Also how can I access object in the key value "username" and "password"? Here is the link for fiddle I tried?
Try this: http://jsfiddle.net/zds6M/3/
var echoOut = function(data){
$.each(data,function(i,v){
if(typeof v == 'object'){
console.log('In: ' + i);
echoOut(v);
}else{
console.log(i + ': ' + v);
}
});
};
data = JSON.parse(data);
echoOut(data);
properties of an object in javascript can be accessed via
for in loop
for (var x in yourobject)
{
// key is x
// value is object[x]
}
if you already know the property name
than use can use yourobject["propertyname"] or yourobject.propertyname