Home > Mobile >  How to use a string data as object?
How to use a string data as object?

Time:03-27

I am new to software development. I am writing an application with React native. I am receiving data from the backend as follows. Actually the data is much bigger but I put a small piece of it.

For example, I want to use the first element in the array as data.Terms[0] Or I need to use the incoming data with .map. But I can't do any of these. When I do JSON.parse, I get the error Error: JSON.parse requires at least one parameter

What do I do to use this data in the ways I specified?

import React from "react";
import { View } from 'react-native';

export default Dropdown = ({ }) => {

    const data = {
        "Terms": "[{\"TermId\":\"12\",\"time\":\"10:00\"},{\"TermId\":\"13\",\"time\":\"13:00\"}]"
    }

    return (
        <View>
        </View>
    )
}

CodePudding user response:

you have mixed a json object and json string in your data. You can only parse a json string, not a json object. So to read data try this

const data = {
  "Terms": "[{\"TermId\":\"12\",\"time\":\"10:00\"},{\"TermId\":\"13\",\"time\":\"13:00\"}]"
}

var terms= JSON.parse(data.Terms);
console.log(terms);

var time=terms[0].time; // 10:00
  • Related