将json导出到json文件

时间:2017-09-03 11:44:10

标签: javascript html json

我正在尝试使用html和js将json导出到文件。

这是我的代码:

<form onsubmit="return make_json(this);">
    name: <input type="text" name="first"/><br>
    <input type="submit" value="JSON"/>
</form>

<pre id="output">
    your json here
</pre>

<script>
    function make_json(form) {
        var json={
            "first": form.first.value
        };

        var str = JSON.stringify(json, 0, 4);
        document.getElementById('output').innerHTML = str;

        return false;
    }
</script>

正如您所看到的,我在jtml中将json显示到主页面,但我不知道如何将其导出到文件中。我找了很长时间的答案,但没有什么帮助我或大多数我无法理解答案。有人可以向我澄清这个吗?

1 个答案:

答案 0 :(得分:2)

我想你想下载一个json作为内容的文件吗?

FileSaver.js让这一切变得简单:https://github.com/eligrey/FileSaver.js/

   .   ____          _            __ _ _
  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
 ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
   '  |____| .__|_| |_|_| |_\__, | / / / /
  =========|_|==============|___/=/_/_/_/
  :: Spring Boot ::        (v1.5.6.RELEASE)


 2017-09-03 16:43:53.881  INFO 6584 --- [           main] c.n.SpringBootMvcExampleApplication      : Starting SpringBootMvcExampleApplication on lenovo-PC with PID 6584 (C:\Users\lenovo\Documents\workspace-sts-3.8.4.RELEASE\SpringBootMVCExample\target\classes started by lenovo in C:\Users\lenovo\Documents\workspace-sts-3.8.4.RELEASE\SpringBootMVCExample)
 2017-09-03 16:43:53.896  INFO 6584 --- [           main] c.n.SpringBootMvcExampleApplication      : No active profile set, falling back to default profiles: default
 2017-09-03 16:43:54.218  INFO 6584 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6e38921c: startup date [Sun Sep 03 16:43:54 IST 2017]; root of context hierarchy
 2017-09-03 16:43:56.213  INFO 6584 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup 2017-09-03 16:43:56.294  INFO 6584 --- [           main] c.n.SpringBootMvcExampleApplication      : Started SpringBootMvcExampleApplication in 3.284 seconds (JVM running for 3.931)
 2017-09-03 16:43:56.297  INFO 6584 --- [       Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6e38921c: startup date [Sun Sep 03 16:43:54 IST 2017]; root of context hierarchy
 2017-09-03 16:43:56.304  INFO 6584 --- [       Thread-3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown