Unable to remove a key value pair from JSON string? - javascript

On doing console.log(data.toString()), I get the following output:
{
"cid":"9333227",
"status" : 30,
"user" : "user1"
}
On doing console.log(data['cid']) before performing delete, I get undefined as the output
I want to remove the cid key value pair such that the console.log(data.toString()) should generate the following output:
{
"status" : 30,
"user" : "user1"
}
I am doing delete data['cid'] and then doing console.log(data.toString()). However, it is still printing the original json
{
"cid":"9333227",
"status" : 30,
"user" : "user1"
}

If you run data.toString()), and get the output you got, means that data is not an object. It's likely a string.
If you run:
"hello".toString();
you get "hello".
If you run:
delete "hello".foo
You are deleting a non-existant property on the string, which works without error. It doesn't change the contents of the string.
So I think you don't have an object, you have a JSON string. To mutate it, you need to first parse it:
const obj = JSON.parse(data);
delete obj.cid;
console.log(obj);
If you need to turn it back into a JSON string, you can use JSON.stringify().

let jsonobj = {
"cid": "933227",
"status": 30,
"user": "user1",
}
delete jsonobj['cid']
console.log(JSON.stringify(jsonobj));
Try JSON.stringify() instead of .toString()

Related

Json parse not convert to object

My API return user object and format is like that=>
{'id': '1', 'username': 'admin', 'image': 'https://user/testing.png', 'phno': '123'}
First I do JSON.stringify and I check the type of this line is a string.
So I use JSON.parse to get an object but its still string and can't get it likes user.id is undefined.
How can I get like user.id, user.username,...?
console.log(user);
console.log(user.user);
var test = JSON.stringify(user.user);
console.log(typeof(test));
var test1 = JSON.parse(test);
console.log(test1.id);
I think the problem might be that your API is returning JSON data with single quotation marks, and JavaScript is not able to parse it correctly. Check which JSON serializer you're using on server side. It should be like: {"id": "1", "username": "admin", "image": "https://user/testing.png", "phno": "123"}.
This solution works for your data:
var data = '{"id": "1", "username": "admin", "image": "https://user/testing.png", "phno": "123"}';
var user = JSON.parse(data);
console.log(user.id);
It seems like you are not getting exact user json. Issue may be backend.
const obj = `{"user":"{\\"id\\": \\"1\\", \\"username\\": \\"admin\\", \\"image\\": \\"https://user/testing.png\\", \\"phno\\": \\"123\\"}"}`
console.log(obj)
// First get value of user.
let user = JSON.parse(obj).user
console.log(typeof user) //string
// parse again, since user is string
user = JSON.parse(user)
console.log(user.username)
console.log(user.id)

Appending a JS array to JSON after writing to and reading the JSON

I'm trying to save data to a JSON file, the first save goes fine, the second save breaks the JSON. Here is what my array looks like (simplified for example):
var myArray1 = new Array ({
Ex1 : "Ex1",
Ex2 : "Ex2",
Ex3 : "Ex3"
});
I save this to JSON, which returns valid json, I read it and try to save another array like this on top of this one:
var myArray2 = new Array ({
Ex4 : "Ex4",
Ex5 : "Ex5",
Ex6 : "Ex6"
});
I've tried using concat which creates this in Chrome Console:
0:
Ex1: "Ex1"
Ex2: "Ex2"
Ex3: "Ex3"
__proto__: Object
1:
Ex4: "Ex4"
Ex5: "Ex5"
Ex6: "Ex6"
__proto__: Object
length: 2
__proto__: Array(0)
I would assume using JSON.stringify now would make it valid JSON but when I save it to JSON it gives me this:
[{
"chosenDate": "May_2019_1",
"shiftName": "Test 1",
"startTime": "00:00",
"endTime": "01:00",
"payPerHour": "1.00"
}]
[{
"chosenDate": "May_2019_16",
"shiftName": "Test 2",
"startTime": "01:00",
"endTime": "02:00",
"payPerHour": "2.00"
}]
The first JSON was the exact same up until the first "]" so concat did nothing in the end? How can I solve this so it makes valid JSON?
I don't know if it changes anything but I'm trying to make an ionicv1 app, using the cordova-file-plugin to save JSON.
EDIT:
So I'm unsure why but when trying to use my example in Chrome it works, but when running it through my app, actually putting it in a file and reading it from the file it returns the broken JSON. The process is:
create first array.
stringify it and write to json file.
read file and parse json.
create second array.
concat the arrays.
stringify and write to json.
and the file has the broken JSON. I guess somewhere in writing it or reading something is not going quite right, also setting it apart from the possible duplicate post.
Your statement:
var myArray1 = new Array ({
Ex1 : "Ex1",
Ex2 : "Ex2",
Ex3 : "Ex3"
});
Creates an array of one object, and you do this twice, so you get two arrays, containing 1 object each.
You must create the first array, then keep pushing to it.
var myArray1 = new Array({
Ex1 : "Ex1",
Ex2 : "Ex2",
Ex3 : "Ex3"
});
myArray1.push({
Ex4: "Ex4",
Ex5: "Ex5",
Ex6: "Ex6"
})
console.log(myArray1)
Allright, from your code it should look like this:
const myArray1 = new Array ({
Ex1 : "Ex1",
Ex2 : "Ex2",
Ex3 : "Ex3"
});
const myArray2 = new Array ({
Ex4 : "Ex4",
Ex5 : "Ex5",
Ex6 : "Ex6"
});
const mergedArray = myArray1.concat(myArray2);
// Merged array is now:
// 0:
// Ex1: "Ex1"
// Ex2: "Ex2"
// Ex3: "Ex3"
// __proto__: Object
// 1:
// Ex4: "Ex4"
// Ex5: "Ex5"
// Ex6: "Ex6"
JSON.stringify(mergedArray, null, 4);
// Returns formatted JSON.
// "[
// {
// "Ex1": "Ex1",
// "Ex2": "Ex2",
// "Ex3": "Ex3"
// },
// {
// "Ex4": "Ex4",
// "Ex5": "Ex5",
// "Ex6": "Ex6"
// }
// ]"
I tried it in Chrome console - it returns valid JSON.
Check what might be different from what you are doing.

JSon File first read as an object then as a Json

So my problem is pretty simple.
I have a Json File which contain : { "message": [] }
In this File I'll add continuously messages by parsing it, pushing an item and "stringifying" it back.
Like this :
jf.readFile(file, 'utf8', function(err, json){
json = JSON.parse(json)
json.message.push({user: message.username, date: message.hour, message: message.text})
json = JSON.stringify(json)
jf.writeFile(file, json, 'utf8');
}
However when it is the first message basicJsonF is consider as an [object Object].
And as soon as I have a message in it is consider as a JSon file.
How could I (without an if condition) specify basicJsonF as a Json File?
Edit :
I've found out a solution I guess is clean if anyone need it :
typeof(json) === 'object' ? null : json = JSON.parse(json)
This Code Snippet works fine for what you wanna do. You only need to write the json into your file.
var message = { username: "TestUser", hour: new Date(), text: "HEY THERE!" };
var jsonBasicFile = '{ "message": [] }';
console.log(jsonBasicFile);
var obj = JSON.parse(jsonBasicFile);
console.log(obj);
obj.message.push({user: message.username, date: message.hour, message: message.text});
console.log(obj);
var json = JSON.stringify(obj);
console.log(json);

how to handle document from mongoDB with _bsontype properties

Hi I'm walking through a JSON array resulting of a query of documents in mongoDB.
The fact is that I'm getting the following behaviour and I'm don’t know why I'm getting this:
in key: _bsontype |value: ObjectID
in key: id |value: S÷¯çò9þ w
in key: _bsontype |value: ObjectID
in key: id |value: S÷¯çò9þ h
in key: _bsontype |value: ObjectID
in key: id |value: S÷¯çò9þ h
in key: name |value: Default Process
in key: processType |value: Public
in key: id |value: BPMNDiagram_1
in key: name |value: procurement subprocess
As you can see, this is wear... this is my code:
function changeIDs(json, map, count){
for(var key in json){
if(json.hasOwnProperty(key))
if(typeof json[key] === 'object')
changeIDs(json[key], map, count);
else{
console.log("in key: "+key + " |value: "+json[key]);
}
}
}
And this is a part of my input ( json parameter ):
[
{
"_id": "538df78eafe7f28d39fe2077",
"processId": "538df71bafe7f28d39fe2068",
"processMeta": {
"id": "538df71bafe7f28d39fe2068",
"name": "Default Process",
"processType": "Public"
},
"diagram": {
"id": "BPMNDiagram_1",
"name": "procurement subprocess"
},
"plane": {
"id": "BPMNPlane_1",
"bpmnElement": "538df71bafe7f28d39fe2068"
}
},
{other objects..},{other objects..}
]
Yes, processId, and _id are generated with the ObjectId function, and seems here where the problem appears, I'm not sure about this, but my guess is that each _bsontype correspond to mongoSB Object Id and this is an object so my function go inside this recursively.. getting the following S÷¯çò9þ w..,Am I right ?
Also seems like if I'm not able to get the "processId" and "_id" keys in my for, because of that, I guess are my _bsontype...
So at the end, my question is, How can I walk through my object without getting that results ?, you have to see there is an "id" property that contains crap data and I don’t want it in my result when looking for all keys id for example, BUT still be able to get the ObjectId.str value for my properties "processId" or "_id".
Thanks in advance.
Just in case, if in the future some other unlucky guy as me get the same problem.
As you can see my function changeIDs get 3 parameters, I just change the json parameter, it was supposed to be a json ( and it was ) you can see my json output as text in my question, so it is a valid json, however I did a parse of a stringify string.. and after that I try it again.. and it was working.
So the solution? newJson = JSON.parse(JSON.stringify(json));
Why? well my better bet is that in this way, when we do a stringify of an object, it object change in the following way:
Undefined values disappear in the result.
Lose prototypes properties
The functions die
For example if a json have an object DATE this object would be stringify as Date.toString(), so it would storage the string representation. and if the function does not have a to string would be undefined.
This last is why after doing an stringify it is working, My function ObjectId() didn't survive to my stringify, but it transform to the string value it contains, that is the Mongo object id value...

Parsing a JSON object-within-an-object in javascript

I have a JSON object that looks like this:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [ {... // contains lots objects with the data I'd like to access } ]
As noted above, I want to access the product array of objects. I can't seem to do this though. I've tried:
console.log(json['cj-api']['products'][0]['product']);
But I get typeError: Cannot read property 'products' of undefined.
What's the correct way to access the array of product (note, singular product, not products). This data is coming from an external source so I can't alter the hyphen in cj-api.
EDIT: Here's what the raw console log of json looks like:
{"cj-api":{"products":[{"$":{"total-matched":"231746","records-returned":"999","page-number":"1"},"product":[{ << lots of data in here>>
EDIT 2: To further clarify, I got this object by running JSON.stringify(result) after I put some XML into XML2js.
i have tried the following JSON structure:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [
{
"a": "a",
"b": "b",
"c": "c"
}
]
}
]
}
};
with the log statement as:
console.log(json['cj-api']['products'][0]['product']);
And result is as follows:
[Object { a="a", b="b", c="c"}]
Well your way of accessing json is absolutely correct. This is for debugging. Try
console.log(json['cj-api']);
console.log(json['cj-api']['products']);
console.log(json['cj-api']['products'][0]);
console.log(json['cj-api']['products'][0]['product']);
Which ever line returns undefined means your json is broken there.
If this doesn't work then you need to check for other similar keys. Maybe they value you are trying to find is actually undefined.
Maybe you are trying to loop. If you are then check for the condition if (JSONStructure[key]==undefined) console.log("Undefined at position ..."). That is the only way if you have valid JSON.
typeError: Cannot read property 'products' of undefined means that json exists, but json['cj-api'] is undefined. If you are sure that you are using the right variable name, I think this might be a scope issue, where you are using an other variable than you intend to. json might be the json string, instead of the array-like object. Try renaming your variable and see if you still get this problem. Otherwise the string is not automatically parsed for you and you'll have to parse it with JSON.parse( ... ).
Edit:
var json = '{ "me": "be an evil string" }';
console.log( json ); //'{ "me": "be an evil string" }'
console.log( json['me'] ); //undefined
console.log( JSON.parse( json )['me'] ); // 'be an evil string'
Since your question is missing the last
}
]
}
}
and others here changed your example and made it work, did you try to correct it?
If not then I suggest you or the dataprovider correct the structure of the reply.
I have tried below json structure
var json={
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": []
}
]
}
}
now json['cj-api']['products'][0]['product'] will work

Categories

Resources