the json data is
"{\"n925D\":1,\"t925D\":23.5,\"h925D\":3276.8,...
I'm replacing the symbol by
var results = post
.replace(/\{/g, '[[')
.replace(/\"/g, '\'')
.replace(/\,/g, '\'],[')
.replace(/\:/g, ',\'')
.replace(/\}/g, '\']]')
.replace(/\\([^u])/g, '$1')
;
console.log(results); shows
[['n925D','1'],['t925D','23.5'],['h925D','3276.8'],...
console.log(query.sql); shows
INSERT INTO table (did,val) SET '[[\'n925D\',\'1\'],[\'t925D\',\'23.5\'],[\'h925D\',\'3276.8\'],
how can I remove the \ actually...
You can't reliably parse JSON (or XML or HTML) with regexes. Instead, parse it, change the data, and re-emit it.
var jsonData = '{\"n925D\":1,\"t925D\":23.5,\"h925D\":3276.8,...';
// Parse it into a hash
var jsonParsed = JSON.parse(jsonData);
// Change the hash in jsonParsed to an array of arrays.
// Convert it back into JSON
jsonData = JSON.stringify(jsonObj);
Related
i have added a json array in session. when i try to access the array, it shows as string. that is without any double quotes. but i want it as json array. Am i missing anything here ? please help.
this is the array :
var login_data = {"success":1, "user":{"id":"13","firstname":"Reda","lastname":"Estyu"},"shop_name" :"Market"}
await FlutterSession().set('session_data', login_data);
var get_data = await FlutterSession().get("session_data");
print(get_data);
after accessing it from session it looks like this :
{success:1, user:{id:13,firstname:Reda,lastname:Estyu},shop_name :Market}
Setting Map returns Map and setting String returns String - makes sense. Encode Map to String before setting.
await FlutterSession().set('session_data', jsonEncode(login_data));
...
var get_data = jsonDecode(await FlutterSession().get("session_data"));
I have a json object which is something like below:
"\"{\\n \\\"Foo\\\" : \\\"1234\\\",\\n}\""
Is it somehow possible to iterate through this json object?I tried but my logic did not work which i feel is basically because of these \n and \ i am unable to iterate.How can i get rid of these unnecessary characters ?
The string you've shown is double-encoded JSON if we assume that you've removed some of the content (it has a trailing , in the JSON, which JSON doesn't allow).
If you run it through JSON.parse, you get a string containing JSON for an object.
If you run that through JSON.parse, you get an object.
E.g.:
const parsedOnce = JSON.parse(str);
const obj = JSON.parse(parsedOnce);
Then you loop through that object's properties in the normal way (for-in, Object.keys, Object.entries, etc.).
Live Example:
const str = "\"{\\n \\\"Foo\\\" : \\\"1234\\\"\\n}\"";
const parsedOnce = JSON.parse(str);
const obj = JSON.parse(parsedOnce);
for (const key in obj) {
console.log(`${key} = ${obj[key]}`);
}
That code is also valid TypeScript (playground link), though if you have a type you can apply to obj so it doesn't default to any, that would be good. (You could apply {[key: string]: any} to it at minimum.)
I am reading a JSON file using fs.readFileSync(fileName, 'utf8'); but the results include newline characters, and the output is getting like:
"{\r\n \"name\":\"Arka\",\r\n \"id\": \"13\"\r\n}"
How do I avoid these characters?
my local file looks like:
{
"name":"Arka",
"id": "13"
}
Its unnecessary to read JSON in using fs.readFileSync(). This requires you to also write a try/catch block around the fs.readFileSync() usage and then use JSON.parse() on the file data. Instead you can require JSON files in Node as if they were packages. They will get parsed as if you read the file in as a string and then used JSON.parse(), this simplifies the reading of JSON to one line.
let data = require(fileName)
console.log(data) // { name: 'Arka', id: '13' }
If you want to serialize the parsed JS object within data to a file without the new line & carriage return characters you can write the JSON string to a file using JSON.stringify() only passing in data.
const {promisify} = require('util')
const writeFile = util.promisify(require('fs').writeFile)
const data = require(fileName)
const serializeJSON = (dest, toJson) => writeFile(dest, JSON.stringify(toJson))
serializeJSON('./stringify-data.json', data)
.then(() => console.log('JSON written Successfully'))
.catch(err => console.log('Could not write JSON', err))
You could read the file and then remove them with a regex:
var rawJson = fs.readFileSync(fileName, 'utf8');
rawJson = rawJson.replace(/\r|\n/g, '');
Keep in mind though that for parsing JSON with JSON.parse, you don't need to do this. The result will be the same with and without the newlines.
I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)
We have empty JSON file
I want to write new JSON objects in this file, and get from it Array of JSON objects (and after simply append new JSONs to array by 'push')
I write to the file incoming JSON object:
fs.writeFileSync(tasks, updatedJsonStr, encoding='utf8');
where
updatedJsonStr = JSON.stringify({"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"});
So in the file we see added object.
After we get from the file our JSON objects:
tasksJsonObj = JSON.parse(fs.readFileSync("tasks.json", "utf-8"));
Append new JSON object as string and write it again:
updatedJsonStr = JSON.stringify(tasksJsonObj) + ',' + JSON.stringify(newJsonTask);
fs.writeFileSync(tasks, updatedJsonStr, encoding='utf8');
So we see 2 JSON objects in the file.
!But when I try to read file with 2 JSON objects - I got an error when reading JSON from the file ([SyntaxError: Unexpected token ,]):
try{
tasksJsonObj = JSON.parse(fs.readFileSync(tasks, "utf-8"));
console.log('aaaaa' + JSON.stringify(tasksJsonObj));
return true;
}catch (err) {
console.log("its not ok!");
console.log(err);
return false;
}
Your JSON formation is wrong,
{"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}, {"newisCompleted":false,"task":"dfgdfg","date":"25.06.2015"}
this is what you will get after concat two JSON stringify, which is also invalid.
Your JSON should be like this
[ {"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}, {"newisCompleted":false,"task":"dfgdfg","date":"25.06.2015"} ]
for that you can do something like this
var tasks = [];
tasks.push( {"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}) );
so your update jsonstr would be
updatedJsonStr = JSON.stringify( tasks );
again if you want to append a new json string, you can do like this
tasksJsonObj = JSON.parse(fs.readFileSync("tasks.json", "utf-8"));
tasksJsonObj.push( newJsonTask );
and then stringify it and write it back to file.
If you are trying to "extend" the object:
https://lodash.com/docs#assign
deep extend (like jQuery's) for nodeJS
If you are trying to "push" new objects into an array, then you're almost there:
var updatedJsonStr = JSON.stringify([{"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}]);
fs.writeFileSync(tasks, updatedJsonStr, encoding='utf8');
var tasksJsonArr = JSON.parse(fs.readFileSync("tasks.json", "utf-8"));
tasksJsonArr.push(newJsonTask);
There's a little problem with what you are writing. If you want to have multiple JSONs next to each other, you should consider putting them into an array:
updatedJsonStr = [];
updatedJsonStr.push(JSON.stringify(tasksJsonObj));
updatedJsonStr.push(JSON.stringify(newJsonTask));
and then write them into file!