How to use numbers in the JSON path with node.js? - node.js

I have this JSON file: (EDITED)
{
"user": {
"S-1-5-21-2659826518-2396530539-1407762326-1001": {
"username":"xyz",
"password":"xyz#123",
"email":"xyz#xyz.com",
"uid": 1100
},
"S-1-5-21-2659826518-2396530539-1407762326-1002": {
"username":"abc",
"password":"abc#456",
"email":"abc#abc.de",
"uid": 2222
}
}
}
(the JSON file is valid)
and I need to get the values out of it. But when I try to parse the JSON file an error appears:
console.log(jsonContent.S-1-5-21-2659826518-2396530539-1407762326-1001.username);
^^^^^
SyntaxError: Invalid or unexpected token
also, the username is underlined red from my syntax highlighter. (so there is something wrong)
So I searched the internet and found nothing about it.
Here is my code:
const fs = require('fs');
const filename = "C:/Users/Jonas/Documents/Visual_Studio_Code/Node.js/json.json"
contents = fs.readFileSync(filename);
jsonContent = JSON.parse(contents);
console.log(jsonContent.S-1-5-21-2659826518-2396530539-1407762326-1001.username);
For the case I need it, I cant edit the problematic part S-1-5-21-2659826518-2396530539-1407762326-1001.
I also tried to set it like this: console.log(jsonContent."S-1-5-21-2659826518-2396530539-1407762326-1001".username); but that's ever wronger.
For any more information please ask.

You need to use the square bracket notation because the property name has hyphens in it which JavaScipt interprets as the minus (-) operator:
jsonContent['S-1-5-21-2659826518-2396530539-1407762326-1001'].username;
Snippet:
const jsonContent = {
"S-1-5-21-2659826518-2396530539-1407762326-1001": {
"username":"xyz",
"password":"xyz#123",
"email":"xyz#xyz.com",
"uid": 1100
},
"S-1-5-21-2659826518-2396530539-1407762326-1002": {
"username":"abc",
"password":"abc#456",
"email":"abc#abc.de",
"uid": 2222
}
}
const name = jsonContent['S-1-5-21-2659826518-2396530539-1407762326-1001'].username;
console.log(name);

Related

Reading JSON using Kotlin

I'd love to know what I'm doing wrong - can't access "links" on my JSON file.
Part of code (MainActivity.kt):
var arr = arrayListOf<String>()
fun read_json() {
var json : String? = null
try {
val inputStream:InputStream = assets.open("links.json")
json = inputStream.bufferedReader().use{it.readText()}
var jsonarr = JSONArray(json)
for (i in 0..jsonarr.length()-1){
var jsonobj = jsonarr.getJSONObject(i)
arr.add(jsonobj.getString("links"))
}
var adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, arr)
json_list.adapter = adapter
}
catch(e : IOException){
}
}
JSON file:
{
"links":
[
"google.com",
"youtube.com",
"facebook.com"
]
}
If I remake JSON file, so it will like in the following JSON file, everything works fine. However, I need to use the previous file. 😒
[
{
"links": "google.com"
}
]
Would really appreciate your help!
I believe you need to get the JSON array first and read strings from it, something like this:
var jsonarr = JSONObject(json).getJSONArray("links")
for (i in 0..jsonarr.length()-1) {
arr.add(jsonarr.getString(i))
}

How can I replace text from a config.json file automatically by a variable in node js

Hi and thank you for your help
I have a config.json file that contains this:
{
"test": {
"hi": {
"text": "Hi ${user.name}"
}
}
}
and I have index.js file that contains:
var config = require('./config.json')
var user = {name: "Test", tag: "#1234")
console.log(`${config.test.hi.text}`) // Output: "Hi ${user.name}"
// Expected output: Hi Test
I want when you change in the config.json the user.name to something like user.tag its automatically replaces him without .replace() function
thank you for your help :D
When using Template literals, the expressions in the placeholders and the text between the backticks (` `) get passed to a function that concatenates the strings into a single string, replacing the values inside $(variable).
This process happens at the time you define the template and cannot be resolved later as you do in your code. Refer to the documentation: Template literals
It would be also a bad coding practise as if the user variable didn't exist in the index.js file it wouldn't give you a compile error, but a nasty runtime error.
The only way to do it is to have your template literal in reach of your variable scope, that means that the template literal can read the variable at the moment it's executed. If you want to have the user instance and the template in different files, you can use a callback function as this:
config.js
const callback = (user) => {
return `Hi ${user.name}`
}
const config = {
callback,
anotherConfig: {
hi: {
example: "This is another config"
}
}
}
export default config;
index.js
import config from './config.js';
const user = {name: "Test", tag: "#1234"};
console.log(config.callback(user))
Output
Hi Test

How to parse JSON with escaped doublequotes, using node.js?

Here is an example of some JSON I am working with:
{"name":"John","attributes":"{\"key\":\"value\"}"}
Here it is again, in a more readable format:
{
"name": "John",
"attributes": "{\"key\":\"value\"}"
}
Notice above that the doublequotes surrounding key and value are escaped. That's necessary, and is valid JSON (checked at jsonlint.com).
I am trying to get the value of "name", but the escaped doublequotes are causing an error.
What am I doing wrong in my node.js code?
var theString = '{"name":"John","attributes":"{\"key\":\"value\"}"}';
var theJSON = JSON.parse(theString);
var theName = theJSON.name;
console.log("name = " + theName);
Below is the output. The error occurs on the 2nd line of my code, where I "JSON.parse()" the string. JSON.parse seems to be removing the backslashes, turning valid JSON into invalid JSON.
undefined:1
{"name":"John","attributes":"{"key":"value"}"}
^
SyntaxError: Unexpected token k in JSON at position 31
Since that part of the data is JSON-within-JSON, you'd parse the JSON, then parse the JSON on the attributes property:
const obj = JSON.parse(json);
obj.attributes = JSON.parse(obj.attributes);
Live Example:
const json = document.getElementById("json").textContent;
const obj = JSON.parse(json);
obj.attributes = JSON.parse(obj.attributes);
console.log(obj);
<pre id="json">{
"name": "John",
"attributes": "{\"key\":\"value\"}"
}</pre>

how to validate hour using express-validator npm

i'm trying to use a express-validator to validate a hour. I sent this json:
{
"hour" : "10:30",
"day":"monday"
}
in the following code:
var regex = new RegExp('/^(10|11|12|[1-9]):[0-5][0-9]$/');
var hour = req.body.hour;
req.check('hour',"error to add hour").matches(regex);
var errors = req.validationErrors();
if(errors){
res.status(400).send(errors);
} else {
res.status(200).json({hour:'hour ok'});
}
the program throws me the following error:
[
{
"param": "hour",
"msg": "error to add hour",
"value": "10:30"
}
]
I think my error is in the validation of the regex. should send me {hour:'hour ok'}... please, help me!!!
I guess it works better if you use
new RegExp(/^(10|11|12|[1-9]):[0-5][0-9]$/);
or
new RegExp('^(10|11|12|[1-9]):[0-5][0-9]$');
If you use a string as an argument to the regexp constructor you have to skip the slashes at the beginning and end of the string.

node.js - Is there any proper way to parse JSON with large numbers? (long, bigint, int64)

When I parse this little piece of JSON:
{ "value" : 9223372036854775807 }
This is what I get:
{ hello: 9223372036854776000 }
Is there any way to parse it properly?
Not with built-in JSON.parse. You'll need to parse it manually and treat values as string (if you want to do arithmetics with them there is bignumber.js) You can use Douglas Crockford JSON.js library as a base for your parser.
EDIT2 ( 7 years after original answer ) - it might soon be possible to solve this using standard JSON api. Have a look at this TC39 proposal to add access to source string to a reviver function - https://github.com/tc39/proposal-json-parse-with-source
EDIT1: I created a package for you :)
var JSONbig = require('json-bigint');
var json = '{ "value" : 9223372036854775807, "v2": 123 }';
console.log('Input:', json);
console.log('');
console.log('node.js bult-in JSON:')
var r = JSON.parse(json);
console.log('JSON.parse(input).value : ', r.value.toString());
console.log('JSON.stringify(JSON.parse(input)):', JSON.stringify(r));
console.log('\n\nbig number JSON:');
var r1 = JSONbig.parse(json);
console.log('JSON.parse(input).value : ', r1.value.toString());
console.log('JSON.stringify(JSON.parse(input)):', JSONbig.stringify(r1));
Output:
Input: { "value" : 9223372036854775807, "v2": 123 }
node.js bult-in JSON:
JSON.parse(input).value : 9223372036854776000
JSON.stringify(JSON.parse(input)): {"value":9223372036854776000,"v2":123}
big number JSON:
JSON.parse(input).value : 9223372036854775807
JSON.stringify(JSON.parse(input)): {"value":9223372036854775807,"v2":123}
After searching something more clean - and finding only libs like jsonbigint, I just wrote my own solution. Is not the best, but it solves my problem. For those that are using Axios you can use it on transformResponse callback (this was my original problem - Axios parses the JSON and all bigInts cames wrong),
const jsonStr = `{"myBigInt":6028792033986383748, "someStr":"hello guys", "someNumber":123}`
const result = JSON.parse(jsonStr, (key, value) => {
if (typeof value === 'number' && !Number.isSafeInteger(value)) {
let strBig = jsonStr.match(new RegExp(`(?:"${key}":)(.*?)(?:,)`))[1] // get the original value using regex expression
return strBig //should be BigInt(strBig) - BigInt function is not working in this snippet
}
return value
})
console.log({
"original": JSON.parse(jsonStr),
"handled": result
})
A regular expression is difficult to get right for all cases.
Here is my attempt, but all I'm giving you is some extra test cases, not the solution. Likely you will want to replace a very specific attribute, and a more generic JSON parser (that handles separating out the properties, but leaves the numeric properties as strings) and then you can wrap that specific long number in quotes before continuing to parse into a javascript object.
let str = '{ "value" : -9223372036854775807, "value1" : "100", "strWNum": "Hi world: 42 is the answer", "arrayOfStrWNum": [":42, again.", "SOIs#1"], "arrayOfNum": [100,100,-9223372036854775807, 100, 42, 0, -1, 0.003] }'
let data = JSON.parse(str.replace(/([:][\s]*)(-?\d{1,90})([\s]*[\r\n,\}])/g, '$1"$2"$3'));
console.log(BigInt(data.value).toString());
console.log(data);
you can use this code for change big numbers to strings and later use BigInt(data.value)
let str = '{ "value" : -9223372036854775807, "value1" : "100" }'
let data = JSON.parse(str.replace(/([^"^\d])(-?\d{1,90})([^"^\d])/g, '$1"$2"$3'));
console.log(BigInt(data.value).toString());
console.log(data);

Resources