JSon File first read as an object then as a Json - javascript

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);

Related

Unable to remove a key value pair from JSON string?

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()

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)

Write JSON with Node.js

I'm trying to push names in a json file. I'm trying to do something like:
socket.on('create json', function(data){
var data = JSON.stringify(Data, null, 2);
fs.writeFile('participants.json', data)
console.log(data);
});
This is only outputting the data that I've send and results in:
{
"type": "Buffer",
"data": [34,69,120,97,109,112,108,101,32,110,97,109,101, 34 ]
}
When I'm writing the file it deletes everything and puts that in.
I'm looking for a way to write:
{
"names":["name1", "name2", "name3"]
}
Any ideas on how to fix and write this?
Help is very much appreciated!
you have to again read your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.
var fs = require('fs')
fs.readFile('participants.json', function (err, data) {
var json = JSON.parse(data);
json.name = ["name1", "name2", "name3"];
fs.writeFile("results.json", JSON.stringify(json))
})

How to get JSON Elements from String(full with JSON object).

I have a JSON file
{ "impressions":
[
{
"impressionId": "7ad7a77fas346a7a2a1da6",
"userId": "hafsa",
"clientId": "400"
},
{
"impressionId": "7ad7a77fas346a7a2a1da7",
"userId": "asif",
"clientId": "200"
},
{
"impressionId": "7ad7a77fas346a7a2a1da8",
"userId": "zadarov",
"clientId": "300"
},
{
"impressionId": "7ad7a77fas346a7a2a1da9",
"userId": "julia",
"clientId": "100"
}
]
}
I am working on Kafka and have a NodeJS Producer and Java Consumer.I have to get each impression as a separate message in my consumer. My nodeJS code is:
console.log("Kafka is recieving JSON....");
var fs = require('fs');
var kafka = require('kafka-node');
var Producer = kafka.Producer;
var Client = kafka.Client;
var client = new Client('localhost:2181');
var producer = new Producer(client);
fs.readFile('data.json', 'utf8', function (err, data) {
if (err) throw err;
var jsonobj = JSON.parse(data);
var countMessages = jsonobj.impressions.length;
var impressionArr = [];
impressionArr = jsonobj.impressions;
payloads = [
{ topic: 'test', messages: impressionArr, partition: 0 }
];
producer.on('ready', function(){
producer.send(payloads, function(err, data){
console.log(data);
});
});
producer.on('error', function(err){
console.log("Error: "+err)
});
});
and my JAVA consumer is :
JavaInputDStream<String> messagesFrmSpecifiedOffset= KafkaUtils.createDirectStream(
sc,
String.class,
String.class,
StringDecoder.class,
StringDecoder.class,
String.class,
kafkaParams,
fromOffset,
new Function<MessageAndMetadata<String, String>, String>() {
public String call(MessageAndMetadata<String, String> msgAndMd) throws Exception {
return msgAndMd.message();
}
}
);
and I am getting impressions as separate messages as follows in JAVA consumer.
JavaDStream<Record> rdd_impressionRecords = messagesFrmSpecifiedOffset.map(
new Function<String, Record>() {
public Record call(String impressions) throws Exception {
System.out.println("impressions: " + impressions);
Record sd = new Record();
return sd;
}
});
BUT MY PROBLEM IS:
that I am getting output in object form like:
impressions: [object Object]
impressions: [object Object]
impressions: [object Object]
impressions: [object Object]
I know that I am sending JSON and recieving as String but anyone can help me to do solution in three ways:
1. Can I get key, values from [object Object] in Java class.
2. Is it possible to send each array element as String (using JSON.stringify) in NodeJS without any loop. Direct transfer as I am doing.
3. Can I rewrite method of createDirectStream that returns JSON obect directly.
In addition to Zdeněk Tisoň answer:
a) First use JSON.stringify() to create a string and send it over the net.
b) At the consumers side transform this string to whatever you want. If you want it to be Json you can use JSON.parse().
Client code could be:
var _ = require('lodash');
var payloads = _.map(JSON.parse(data).impressions, function(imp){
return JSON.stringify(imp);
});
producer.send(payloads, function(err, data){
});
Spark code could use json-simple library:
import org.json.simple.*;
JSONObject imp = (JSONObject) JSONValue.parse(impression);
String impressionId = (String) imp.get("impressionId");
You could use Java's JSONObject to get the string as a JSONObject like so:
JSONObject jsonObject = new JSONObject(impressions)
Then use the JSONObject functions to get what you need as listed here:
http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
Use JSON.stringify before sending messages onto the Kafka bus. For example, your code changes to messages: JSON.stringify(impressionArr).
AFAIK producing object to kafka is not supported by kafka-node. If you try to do that, the object itself would be in format of [object Object], actually it's String '[object Object]'. That's why you can not de-serialize from Java.
try JSON.stringify(impressionArr) when produce in your node code and some JSON library when consume from Java side.

Adding to a JSON string

I have a JSON string as follows:
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
It is generated after calling this function in KnockOut:
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
TypeName: line.category().TypeName,
TypeID: line.category().TypeID
: undefined
});
alert(JSON.stringify(dataToSave));
However, I want to add 3 more pieces of information to the model, before posting it back to my server - to also send Name, Email and Tel:
{
"Name":"Mark",
"Email":"me#me.com",
"Tel":"0123456789",
"Rooms":
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
}
Is there a proper way of adding this information to the JSON, or is it just as simple as:
var toSend = "{\"Name\":\"Mark\":\"Email\":\"me#me.com\", \"Tel\":\"0123456789\",\"Rooms\":"
+ JSON.stringify(dataToSave) + "}";
Thank you,
Mark
Parse your JSON string using JSON.parse into a valid JS object, add the data to the object as needed, then JSON.stringify it back. A JSON string is just a representation of your data, so you shouldn't rely on modifying it directly.
Why encode to JSON and then modify the resulting string when you can pass the structure you actually want to the JSON encdoder?
var toSend = JSON.stringify({
Name: "Mark",
Email: "me#me.com",
Tel: "0123456789",
Rooms: dataToSave
});

Categories

Resources