I'm trying to dynamically build a vuetify component in a nuxt project (Using different text values with vuetify component) by importing and iterating through json in a module (https://hackernoon.com/import-json-into-typescript-8d465beded79).
My json in /static/info.json is:
{
"id": 1,
"name": "Johnson, Smith, and Jones Co.",
"amount": 345.33,
"Remark": "Pays on time"
}
In my vue component I have:
import * as data from '../static/info.json';
const word = data.name;
console.log(word); // output 'testing'
console.log(data); // output 'testing'
var jsonData = JSON.parse(data);
// console.log(jsonData); // output 'testing'
The line:
var jsonData = JSON.parse(data);
causes:
Cannot convert object to primitive value
How can I iterate through the imported json?
I would guess data is already an object and doesn't need to be parsed again. The import has turned it into an object. You've already used it with data.name
Related
I recently exported all my user data from Firebase and now I want to format the JSON file to filter only the relevant field I need for my data model.
The file I got on Firebase is currently stored like this:
{
"Users": {
"00uniqueuserid3": {
"1UserName": "Pusername",
"2Password": "password",
"3Email": "email#gmail.com",
"4City": "dubai"
}
}
}
The issue is that the JSON file got over 5,000 users and I cannot get possibly manual format them how I want them. Is there any Javascript script or tool I can use to reformat all the data in the file, I would like to format them as such:
{"id": uniqueid , "name": name, "email": email, "city": city}
You can create a new NodeJS project (npm init -y) and install mongodb. Then read the JSON file and modify the format using JS:
const mongodb = require("mongodb")
const exportedData = require("./myFirebaseExport.json");
const db = "" // <-- Mongo Client
const data = Object.values(exportedData.Users);
const parsedData = data.map((d) => {
// modify the data array as required;
return {
name: d.username, // replace with your field names
email: d.Email,
}
})
await db.collection("users").insertMany(parsedData);
I created a JSON file as follows
{
"fooditems" : [
{
"name": "pizza",
"type": "fastfood",
"price": 10
},
{
"name": "apple",
"type": "fruit",
"price": 1
}
]
}
created a JS file to read the JSON file
const data = require("./data.json");
data1 = JSON.parse(data);
data1.foodData.forEach( foodItem => console.log(foodItem));
When I run the JS, I get error for the json file
Syntax error: Unexpected token o in json at position 1
at JSON.parse
You don't need to parse data since it's already and object. The following should work.
const data = require("./data.json");
data.fooditems.forEach( foodItem => console.log(foodItem));
Note foodData was change to fooditems based on the contents of the data.json file.
Your initial data JSON contains "fooditems", but in the JS file you are trying to process the "foodData". Change the "foodData" to "fooditems" and it should work.
I think that you are trying to access invalid object key in your JS file on the last line.
Instead of
data1.foodData
put
data1.fooditems
I have a JSON file that I am using javascript to read, I am able to print it out in console, but I have to manually code the number of objects in the JSON file, the file is really simple with only 3 objects, I would like to create a function that checks how many objects are in JSON file.
Json Code
{
"items": [
{
"fname": "Kali",
"lname": "Flower",
"age": "19"},
{
"fname": "JD",
"lname": "Wyatt",
"age": "19"
}]
}
I'm trying to write a javascript function showing how many objects are in it
Use JSON.parse to convert the content to object then use .length to get the size:
JSON.parse(fs.readFileSync(file)).items.length
Explained:
const fs = require("fs"); // require fs
const content = fs.readFileSync(file); // read the file content as string
const obj = JSON.parse(content); // convert string to object
const length = obj.items.length;
I want to model the following information into json but am unable to do so.
The server sends result of an operation to the client using the following model
class Result (result:string, additional-info:string)
additional-info could contain a json or a string depending on the use case. Thus its type is String. When I need to send a json in it, I simply send a string with a valid json syntax and I suppose the the Angular client would be able to convert the string into a json using JSON.parse.
The json I want to send to the client looks like
{
"result": "success",
"additional-info": {
"list ": [{
"tag": "sometag",
"description": "some description"
}]
}
}
I checked on jsonlint (https://jsonlint.com/) that the structure is correct.
On the client side (Angular), I am handing the message as follows:
getQuestions(some args){
console.log('response from server:',res)
console.log('response body',res.body)
let jsonResponse:ServerResponseAPI = res.body //should contain result and additional info
console.log("result: "+jsonResponse.result+", additional info:"+jsonResponse.additionalInformation)
let jsonList:string = jsonResponse.additionalInformation
console.log("jsonQuestionList: "+jsonList)
let information:Information = JSON.parse(jsonList)
console.log("information:"+information)
});
}
ServerResponseAPI is defined as
export class ServerResponseAPI{
constructor ( public result:string,
public additionalInformation:string){}
}
When I execute the code, I see the following prints on browser's console but I see that error that additional-info is not define.
response body {result: "success", additional-info: "{"list ": [{"tag": "sometag", "description": "some description"}]}"}
list-management.service.ts:46 result: success, additional info:undefined
I can see that the body contains result and additional-info but after casting the body to ServerResponseAPI, I see that result is success but additional-info is undefined.
in res.body, javascript creates an object
{
"result": "success",
"additional-info": {
"list ": [{
"tag": "sometag",
"description": "some description"
}]
}
}
The object has two keys - result and additional-info. Lets call it Object1
I assign it to an object which has keys result and additionalInfo. Note the difference in naming convention in additionalInfo. In javascript, names of variables are case sensitive, so the above two are different. Lets call this object2
Now result from object1 gets assigned to result from object2 because the keys match (same name result)
additional-info becomes a new key in the object2
additionalInfo key of object2 stays undefined as no key from object1 maps to additionalInfo
To solve the issue, I had to create a additional-info key ServerResponseAPI (alternatively I could have also changed my JSON property name to additionalInfo but I didn't want to change that). This is done in Angular as
export class ServerResponseAPI{
'additional-info':string;
constructor ( public result:string,
public additionalInformation:string){
this['additional-info'] = additionalInformation;
}
}
In my code, I now access the keys as
let jsonResponse:ServerResponseAPI = res.body //contains result and additional info
console.log("result: "+jsonResponse.result+", additional info:"+jsonResponse['additional-info'])
let jsonQuestionList:string = jsonResponse['additional-info']
I am using the node.js to interpret a JSON data, the data format is like this below
{
"href": "https://localhost/light/0000293D",
"i-object-metadata": [
{
"rel": "temperature",
"val": "244"
}
]
}
I can print the raw data using print (body)
to interpret data all works except printing the field i-object-metadata
var obj = JSON.parse(body);
console.log(obj.items); // works well
console.log(obj.i-object-metadata); // error
How could I interpret the JSON object like this i-object-metadata
Can't use the object shorthand in this case, you'll have to use the array notation:
console.log(obj['i-object-metadata'].val); // 244