React Native 中的 JSON Fetch 解析问题

茶柚木

我目前正在尝试在本机反应中迭代 json。JSON 有可变数量的返回,其格式非常奇怪,不幸的是我无法更改 JSON 的创建方式,因此我希望获得有关如何正确解析它的建议。

这是应该 fetch() json 并显示值的代码:

import React, { useState, useEffect } from "react";
import { ActivityIndicator, FlatList, SafeAreaView, StatusBar, StyleSheet, Text, View, TouchableOpacity } from "react-native";

const App = () => {
  const [selectedId, setSelectedId] = useState(null);
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState({});
  const [counter, setCounter] = useState(0);

  const getJSON = async () => {
    const response = await fetch('URL');
    const json = await response.json();
    setData(json.Items);
    setCounter(json.Count);
    setLoading(false);
  }

  useEffect(() =>{
    getJSON();
  }, []);

  return (
    <View style={{ flex: 1, padding: 24 }}>
    {isLoading ? <ActivityIndicator/> : (
      <FlatList
        data={data}
        keyExtractor={({ Items }, index) => id}
        renderItem={({ item }) => (
          <Text>{item.Items}</Text>
        )}
      />
    )}
  </View>
  );
};

这是 fetched() 的 JSON:

{
    "Count": 1,
    "Items": [{
        "building": {
            "S": "Wash"
        },
        "mac": {
            "S": "FF:FF:FF:FF:FF:FF"
        },
        "name": {
            "S": "test asset"
        },
        "asset_id": {
            "S": "01"
        },
        "floor": {
            "S": "1"
        },
        "room": {
            "S": "102"
        }
    }],
    "ScannedCount": 1
}

任何帮助,将不胜感激。我对解析 JSONS 还是很陌生

德鲁里斯

我建议将响应值预处理Items为更可用的格式来呈现。您需要“解包”S每个嵌套外部键的嵌套属性。然后,您可以item更轻松地映射/访问元素属性。

例子:

const { Items } = {
  Count: 1,
  Items: [
    {
      building: { S: "Wash" },
      mac: { S: "FF:FF:FF:FF:FF:FF" },
      name: { S: "test asset" },
      asset_id: { S: "01" },
      floor: { S: "1" },
      room: { S: "102" }
    },
  ],
  ScannedCount: 1
};

const data = Items.map((obj) =>
  Object.entries(obj).reduce((items, item) => {
    const [key, { S: value }] = item;
    return {
      ...items,
      [key]: value
    };
  }, {})
);

console.log(data);

代码:

function App() {
  const [selectedId, setSelectedId] = useState(null);
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [counter, setCounter] = useState(0);

  const getJSON = async () => {
    const response = await fetch("URL");
    const json = await response.json();
    const { Count, Items } = json;

    const data = Items.map((obj) =>
      Object.entries(obj).reduce((items, item) => {
        const [key, { S: value }] = item;
        return {
          ...items,
          [key]: value
        };
      }, {})
    );

    setData(data);
    setCounter(Count);
    setLoading(false);
  };

  useEffect(() => {
    getJSON();
  }, []);

  return (
    <div className="App">
      {isLoading ? (
        <h2>Loading...</h2>
      ) : (
        <FlatList
          data={data}
          keyExtractor={({ asset_id }) => asset_id}
          renderItem={({ item }) => (
            <View key={item.asset_id}>
              <Text>
                Location: {item.building} {item.floor}-{item.room}
              </Text>
              <Text>Name: {item.name}</Text>
              <Text>MAC: {item.mac}</Text>
              <Text>Asset Id: {item.asset_id}</Text>
            </View>
          )}
        />
      )}
    </div>
  );
}

编辑 json-fetch-parsing-issues-in-react-native

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 React Native fetch 方法中解析 JSON 不起作用

React-Native Fetch +在iOS Simulator中解析JSON爬网,但在远程调试中即时

无法解析通过 React 中的 fetch 方法返回的 JSON 数据

.catch() 在 react-native 的 fetch 中

针对使用react-native中的fetch检索的json对象验证数据

如何在React Native中解析JSON数据

在React Native中解析对FlatList的JSON数组响应

解析JSON以在React Native中建模未定义

React Native Fetch异步

在 React Native 中显示 JSON

使用Fetch React Native时获得不同的JSON响应

React Native fetch()返回奇数json响应项

如何使用React Native Fetch()从API检索格式错误的json

无法在 React Native 中使用 Javascript 'fetch' 发布 JSON?

react-native 尝试解析内置的 fetch 函数

在React中传递数据的Fetch / TemplateLiteral问题

React Native 中的 Flex 问题

React Native中的RCTImage问题

React Native 中的 AsyncStorage 问题

React Native中的`fetch`不会从URL返回预期的数据

在类方法 React Native 中包装 fetch API

如何在 React Native 中抛出 Catch in fetch POST 请求

如何在React Native的Fetch函数中设置超时

react native中的axios和fetch有什么区别?

我在通过 react native 解决 android 上的 fetch 结果时遇到了 react native 的问题

AppAuth 语义和解析问题正在破坏 xcode 中 React Native 项目的构建

React-Native:借用JSON对象的问题

PHP中解析JSON的问题

React Native fetch 在另一个 fetch 回调中不起作用