我正在使用Reaction从包含JSON对象的输入字段中读取值.

我能够将JSON字符串值转换为包含以下内容的常量:

{"name":"This is the name element"}

但是,当我try 从JSON中提取"name"元素的值时,我得到了一个"未定义"的响应.

当我从js文件中获得相同的JSON文本时,如下所示:

export default
    {"name":"This is the name field"}

并使用以下命令导入:

import JSONObject from './JSONObjectFile'

那么它就运行得很好.

在从HTML页面上的文本字段检索JSON对象时,我需要做什么才能实现相同的功能?

以下是完整的代码:

import './App.css';
import JSONObject from './aa_DDFFormConfigJSON'

function App() {
  var myJSON;

  function ConfigJSONReady(event) {
    myJSON = document.getElementsByName("myJSONField")[0].value;
    //This returns "undefined" instead of the actual "name" element value 
    console.log("myJSON.name using input field: " + myJSON.name); 

    // This is the same JSON object from a file, but it works fine
    myJSON = JSONObject;
    console.log("myJSON.name using file import: " + myJSON.name); 
  }

  return (
    <div>
      <header>
        Everything here is in a REACT App
        <p>Success!!</p>
      </header>

      <form>
        <textarea rows="10"
          cols="200"
          maxlength="5000"
          id='myJSONField'
          defaultValue='{"name":"This is the name field"}'>
        </textarea>
        <input
          name="DDFConfigJSONReady"
          id="DDFConfigJSONReady"
          type="checkbox"
          onChange={ConfigJSONReady}
        />

      </form>
    </div>
  );


}

export default App;

推荐答案

您使用了错误的API来获取textarea值,您没有将name属性值赋予元素.

<textarea rows="10"
  cols="200" // you are missing `name="myJSONField"` 
  maxlength="5000"
  id='myJSONField'
  defaultValue='{"name": "This is the name field"}'>
</textarea>

相反,您可以使用document.getElementById(),因为您已经为元素指定了id.

从元素得到的value是一个文本,您应该使用JSON.parse()将其解析为JSON.

因此,代码将如下所示:

myJSON = document.getElementById("myJSONField").value;
//This returns "undefined" instead of the actual "name" element value
console.log("`myJSON.name` using input field: " + JSON.parse(myJSON).name);

// This is the same JSON object from a file, but it works fine
myJSON = JSONObject;
console.log("myJSON.name using file import: " + myJSON.name);

现场演示:https://codesandbox.io/s/funny-raman-ktvdzi?file=/src/App.js:141-513

Json相关问答推荐

Azure Data Factory JSON输出格式问题

通过在织女星简化图上裁剪来显示文本

Postgres Select json数组并重新映射属性名称

序列化从/到空值

在Jolt中将具有嵌套元素的对象数组转换为单独的对象列表

展平多个数组以保持顺序

迭代powershell双维json对象

将来自 Golang 的 JSON API 调用响应输出到 nextjs 前端

将具有多个级别的 json 读入 DataFrame [python]

Scala - 在构建 Json 时无法删除 Key -> value "{}" 大括号的双引号

JQ 中的样本标准偏差

boost::json::value 的大括号初始化将其从对象转换为数组

如何在 Node.js 中解析包含NaN的 JSON 字符串

如何判断 Json 对象中是否存在键并获取其值

.NET CORE 3 升级 CORS 和 Json(cycle) XMLHttpRequest 错误

Json.Net:用于自定义命名的 JsonSerializer-Attribute

Golang struct 的 XML 和 JSON 标签?

如何使用 SwiftyJSON 将字符串转换为 JSON

如何在 Django JSONField 数据上聚合(最小/最大等)?

如何将 mysqli 结果转换为 JSON?