Home > Software engineering >  How to I import an array (in js formating) from a json file?
How to I import an array (in js formating) from a json file?

Time:12-12

I want import an array from a json file which only contains this array. in this app, I want to perform a search on this array. so it must be recieved in the array formating.

this is a part of long array exsisting in cities.json :

cities.json:

[ "Aberdeen", "Abilene", "Akron", "Albany", "Albuquerque", "Alexandria", "Allentown", "Amarillo", ..., ..., ..., "Yonkers", "York", "Youngstown" ]

enter image description here

In App code, I have displayed the input of the JSON file inside the p tag, Just to see what I get.

index.jsx:

import React from "react";
import ReactDOM from "react-dom";
import text from "./cities.json";

class App extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            value: '',
            hint: ''
        }
    }

    handleChange = (e) => {
        this.setState({
            value: e.target.value
        });

    }

    render() {
        return (
            <div>
                <p>{text}</p>
                <input value={this.state.value} placeholder={this.state.hint} onChange={this.handleChange}/>
            </div>
        );
    }
}

ReactDOM.render(<App/>, document.getElementById("root"));

But I see output is only a text.

enter image description here

How to I recieved that in the array form?

CodePudding user response:

It may already be in array form, that's probably just how react renders arrays. Try an array operation on the value.

text.filter(city => city.startsWith('A'))

If that doesnt work you may need to parse the JSON first.

let parsedText = JSON.parse(text)
parsedText.filter((city) => city.startsWith("A"));

CodePudding user response:

Yo, did you try JSON.parse(array)? :)

  • Related