I'm trying to import a really large JSON file inside a TypeScript file. When I use it my IDE tells me that Property 'length' does not exist on type '{}', when the JSON is clearly an array. How could I fix this?
This is my code:
TS file:
import cities from "./cities.json"
const printData = () => {
console.log(cities.length)
}
JSON file:
[
{ "country": "Andorra", "name": "Sant Julià de Lòria" },
{ "country": "Andorra", "name": "Pas de la Casa" },
{ "country": "Andorra", "name": "Ordino" },
{ "country": "Andorra", "name": "les Escaldes" },
{ "country": "Andorra", "name": "la Massana" },
{ "country": "Andorra", "name": "Encamp" },
... + 128K more objects
]
I've seen that it can come from the size of the file, and that I should use a .d.ts file to declare it. I tried this:
let cities: {
country: string
name: string
}[]
export declare module "./cities.json" {
cities
}
But to call the object I need to call it twice like this:
import cities from "./cities"
const printData = () => {
console.log(cities.cities.length)
}
How could I fix this? Thanks!
Actually, I think this approach is useful. The only thing that you could change is the way that you are importing the information. You can destructure the object that you are importing.
Before:
import cities from "./cities"
After
import {cities} from "./cities"
With that you can use cities.length with no hesitation!
You can use object destructuring to get cities out of cities. For a simple one-liner solution, use this code.
import { cities } from "./cities";
This means that you can use only one cities for getting the length!
cities.length;
This will solve your issue, and also increase code readability.
Related
Try to read json file from another directory in React for options of react-select. It doesn't matter when writing json in the same file, but it doesn't work when reading from another file because it includes number of array.
1: {value: "America/New_York"name: "New York (Eastern)"}
2: {value: "America/Chicago", name: "Chicago(Central)"}
3: {value: "America/Denver", name: "Denver(Mountain)"}
4: {value: "America/Phoenix", name: "Phoenix (MST)"}
I want to remove number key.
Ideal case:
{ "value": "America/Puerto_Rico", "name": "Puerto Rico (Atlantic)" },
{ "value": "America/New_York", "name": "New York (Eastern)" },
{ "value": "America/Chicago", "name": "Chicago (Central)" },
{ "value": "America/Denver", "name": "Denver (Mountain)" }
The code:
timezone.json
[
{value: "America/New_York", name: "New York (Eastern)"},
{value: "America/Chicago", name: "Chicago (Central)"},
{value: "America/Denver", name: "Denver (Mountain)"}
]
app.js
import timezone from "./data/timezone";
console.log("timezzone", timezone);
If the json file looks like something like this:
{
1: {value: "America/New_York", name: "New York (Eastern)"},
2: {value: "America/Chicago", name: "Chicago(Central)"},
3: {value: "America/Denver", name: "Denver(Mountain)"},
4: {value: "America/Phoenix", name: "Phoenix (MST)"},
}
You can simply convert it to an array:
import timezone from "./data/timezone";
console.log(Object.values(timezone));
Object.values:
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. (The only difference is that a for...in loop enumerates properties in the prototype chain as well.)
I have fake users.json file and I can http.get to list the array of json.
Since I want to get the particular user by id and haven't stored the data in the database, instead just use the fake json data.
[
{
"id": "cb55524d-1454-4b12-92a8-0437e8e6ede7",
"name": "john",
"age": "25",
"country": "germany"
},
{
"id": "ab55524d-1454-4b12-92a8-0437e8e6ede8",
"name": "tom",
"age": "28",
"country": "canada"
}
]
I can do this stuff if the data is stored in the database, but not sure how to proceed with the fake json data.
Any help is appreciated.
Thanks
If you need the json as raw data, for just fake data, You can simply require it and use it as object..
const JsonObj = require('path/to/file.json')
console.log(JsonObj[0].id) // <-- cb55524d-1454-4b12-92a8-0437e8e6ede7
Plus, if you need more dynamic solution, there is a good JSON-server you can easily use for testing and so: check this git repo
var _ = require('underscore');
var dummyJson = [
{
"id": "cb55524d-1454-4b12-92a8-0437e8e6ede7",
"name": "john",
"age": "25",
"country": "germany"
},
{
"id": "ab55524d-1454-4b12-92a8-0437e8e6ede8",
"name": "tom",
"age": "28",
"country": "canada"
}
]
var requiredID = "cb55524d-1454-4b12-92a8-0437e8e6ede7";
var reuiredObject = _.find(dummyJson, function (d) {
return d.id === requiredID;
})
Get JSON object using JSON.parse('users.json') and store it in a variable users.
Loop through array of users using for .. in and using if condition on id update the object if required.
Stringify the updated users object using JSON.stringify(users); and write this string to users.json file using fs.write() module in NodeJS so you will have updated objects in your json file.
I have a bunch of JSON files, thousands of different schemas. Using GenSON (the Python JSON schema generator), I managed to create schema files for each of the input files. Now, what I'd like to do is standardize all these different files to one defined schema. Here's an example:
Input
{
"name": "Bob Odenkirk",
"title": "Software Engineer",
"location": {
"locality": "San Francisco",
"region": "CA",
"country": "United States"
},
"age": 62,
"status": "Active"
}
Output
{
"names": ["Bob Odenkirk"],
"occupations": ["Software Engineer"],
"locations": ["San Francisco, CA"]
}
Essentially, I am looking for a language agnostic method (i.e., I don't care what programming language is used) of defining how an input JSON file should be parsed to an output JSON file.
The url https://github.com/bazaarvoice/jolt#jolt
says that Jolt may be what you're looking for.
Jolt
JSON to JSON transformation library written in Java where the "specification" for the transform is itself a JSON document.
Useful For
Transforming JSON data from ElasticSearch, MongoDb, Cassandra, etc before sending it off to the world
Extracting data from a large JSON documents for your own consumption
Jolt Spec
[
// First build the "city, state" string for location
{
"operation": "modify-default-beta",
"spec": {
"location": {
"locConcat": "=concat(#(1,locality),', ',#(1,region))"
}
}
},
// Then map the fields as needed to positions in an output json
{
"operation": "shift",
"spec": {
"name": "name[0]",
"title": "occupations[0]",
"location": {
"locConcat": "locations[0]"
}
}
}
]
I am not sure is your expecting like below. Long time back I have created flat object and output format object. It will return output format object with data filled.
var input = {
"name": "Bob Odenkirk",
"title": "Software Engineer",
"location": {
"locality": "San Francisco",
"region": "CA",
"country": "United States"
},
"age": 62,
"status": "Active"
};
var outputFormat = {
"name": "name",
"occupations": "title",
"locations": "location.locality, location.region"
};
var flatInput = {};
function generateFlatInput(input, parent){
for (var prop in input) {
if(input.hasOwnProperty(prop) && typeof input[prop] === 'object')
flatInput = generateFlatInput(input[prop], parent + prop + '.');
else
flatInput[parent + prop] = input[prop];
}
return flatInput;
}
function generateOutput(input, outputFormat, delimiter){
input = generateFlatInput(input, '');
for (var prop in outputFormat) {
var fields = outputFormat[prop].split(delimiter);
var fieldValue = [];
for(i = 0; i < fields.length; i++){
if(!input.hasOwnProperty(fields[i].trim())) continue;
fieldValue.push(input[fields[i].trim()]);
}
outputFormat[prop] = fieldValue.join(delimiter);
}
return outputFormat;
}
console.log(generateOutput(input, outputFormat, ', '));
https://jsfiddle.net/u2yyuguk/1/
I think the best, fastest, easiest way to parse many JSON files together is using python.
I was doing something similar to your project and ran into the same problem.
I found this site which teaches how to use python to actually parse JSON files together. Turns out there is a library on python called json(use pip to download json dependencies) which enables JSON file processing. If you already have a python editor, This method would be easier and faster then using Jolt
Check This website for more info: https://code.tutsplus.com/tutorials/how-to-work-with-json-data-using-python--cms-25758.
You can also use JS, which is again faster than Jolt. this is the website: https://learn.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript . It is very easy as you can use JSON.parse() function
I'm trying to generate a JSON file with mustache with the following template:
{
"name": "{{customer_info.first_name}}",
"email": "{{contact_info.email}}",
"campaign": {
"campaignId": "{{contact_info.campaign.campaignId}}"
},
"tags": [
{{#contact_info.tags}}
{
"tagId": "{{tagId}}"
},
{{/contact_info.tags}}
]
}
As an output example I get:
{
"name": "Antonio",
"email": "myemail#gmail.com",
"campaign": {
"campaignId": "pfft"
},
"tags": [
{
"tagId": "6prrtAP"
},
{
"tagId": "64rrrE9"
},
]
}
Which unluckily is a BAD FORMATTED JSON, because there is a not wanted "," after the last element in the array.
Can any of you help me in solving this issue and remove the comma ?
Thanks a lot
Try using SelectTransform npm package. It has Mustache like syntax without all the side-effects that Mustache creates and the package size is also not as heavy as Handlebars.js
import ST from "stjs";
const data = {
name: 'Jakub',
friends: [
{
name: 'Michal'
}
]
};
const template = {
newName: '{{ name }}',
friends: {
'{{ #each friends }}': {
subName: '{{ name }}'
}
}
};
console.log(ST.select(data).transformWith(template).root());
// Result:
/**
* {
* "newName": "Jakub",
* "friends": [
* {
* "subName": "Michal"
* }
* ]
* }
*/
I would do this:
var md = {};
var tagsCount = 2;
var currTagIndex = 0;
md['show_comma'] = function(){
currTagIndex++;
return currTagIndex <= tagsCount;
}
Then in Mustache template:
{{#show_comma}}
,
{{/show_comma}}
I've been experiencing some similar problem and I found out that Handlebars is a lot similar to mustache and way more powerful.
You could check that out and try using this template to solve your problem, without adding anything to your current model.
{
"name": "{{customer_info.first_name}}",
"email": "{{contact_info.email}}",
"campaign": {
"campaignId": "{{contact_info.campaign.campaignId}}"
},
"tags": [
{{#each contact_info.tags}}
{
"tagId": "{{tagId}}"
}{{#unless #last}},{{/unless}}
{{/each}}
]
}
Don't generate JSON from textual templates. You'll constantly face problems like this. Superfluous commas, meta characters in strings (what if customer_info.first_name contains double quotes), failing to properly nest structures etc.
Generate your data as native structures in your programming language, and encode it as JSON using library provided by your programming language.
However, if you absolutely need, try to generate as much JSON data as possible (ideally, self-contained JSON fragment) outside template, and interpolate that inside template. For example:
let contact_info = {"tags": [ "6prrtAP", "64rrrE9" ]}
let tags = contact_info.tags.map((tag) => ({"tagId": tag})); // [{tagId: "6prrtAP"}, {tagId: "64rrrE9"}]
let tagsJSON = JSON.stringify(tags); // "[{\"tagId\":\"6prrtAP\"},{\"tagId\":\"64rrrE9\"}]"
Then, pass tagsJSON to your template:
{
"name": "{{customer_info.first_name}}",
"email": "{{contact_info.email}}",
"campaign": {
"campaignId": "{{contact_info.campaign.campaignId}}"
},
"tags": {{tagsJSON}}
}
That way, tagsJSON always contains valid JSON-encoded data, so it might be safely interpolated as a value in JSON dictionary/object. Even if tag list is empty, even if tag IDs suddenly start to contain characters that need escaping etc. All corner cases are already handled for you.
This looks like a good answer:
contact_info['tags'][ contact_info['tags'].length - 1 ].last = true;
and the template would be
{{#contact_info.tags}}
{
"tagId": "{{tagId}}"
} {{^last}}, {{/last}}
{{/contact_info.tags}}
Source: https://stackoverflow.com/a/7591866
I'm playing around with python and JSON files. I'm doing a simple game as a learning project, but I can't fetch a nested key in a list on demand when I want to. In the below example I'm trying to get the name of the player.
This is the JSON file (player_sheet_daniel.json):
[
{
"sheet_header": {
"player name": "Daniel",
"character name": "Ulrik the Blob"
}
},
{
"prim_attr": {
"STR": "11",
"DEX": "12",
"HP": "15",
"SKI": "16"
}
}
]
I've tried:
import json
with open('player_sheet_daniel.json','r') as sheet_json:
sheet_py = json.load(sheet_json)
for section in sheet_py:
print(section['sheet_header']['player name'])
I get: KeyError: 'sheet_header'.
Your JSON example is an array which wraps two objects. So, the correct python syntax would be :
import json
with open('player_sheet_daniel.json','r') as sheet_json:
sheet_py = json.load(sheet_json)
section = sheet_py[0]
print(section['sheet_header']['player name'])