I made a JSON file with multiple objects containing named values assigned to strings like this,
{
"Obj1" : {
"Val1": "Obj 1, Test Value 1",
"Val2": "Obj 1, Test Value 2",
"Val3": "Obj 1, Test Value 3"
},
"Obj2" : {
"Val1": "Obj 2, Test Value 1",
"Val2": "Obj 2, Test Value 2",
"Val3": "Obj 2, Test Value 3"
}
}
I needed to access each value in each object individually in Next JS, I tried to import and parse the data,
import data from '~/data.json';
const obj1: any = JSON.parse(data["Obj1"]); // Side Note: What type should this const be?
console.log(obj1.Val1); // Desired Output: " Obj1, Test Value 1 "
Although, when I attempted this I ran into this error, " Argument of type '{ Val1: string; }' is not assignable to parameter of type 'string'.ts(2345) "
I cannot find how to get around this error no matter what I do. Is my JSON or TS incorrect?
The issue is in the JSON.parse(data["Obj1"]);
expression.
By doing JSON.parse(data["Obj1"]);
you are actually calling JSON.parse
on this object:
{
"Val1": "Obj 1, Test Value 1",
"Val2": "Obj 1, Test Value 2",
"Val3": "Obj 1, Test Value 3"
}
However, JSON.parse
requires a string as argument (and the string will be converted to an object). Example:
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
Therefore, you can solve your problem and get the Val1
value by just doing:
import data from '~/data.json';
// In Next.js + TS, by default the `data` object should be already correctly typed as an object.
// However, if this is not the case, you can type it manually with an interface
// or with the object type Record<K, T>
const obj1: Record<string, string> = data["Obj1"];
console.log(obj1["Val1"]); // Output: "Obj1, Test Value 1"