如何将JSON字符串转换为具有不同结构的JSON字符串

如何将JSON字符串转换为具有不同结构的JSON字符串

本文介绍了如何将JSON字符串转换为具有不同结构的JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个应用程序,其中从第三方系统检索数据作为JSON字符串。我需要将此JSON字符串转换为另一个具有不同结构的JSON字符串,以便它可以与内部Javascript库中定义的预先存在的函数一起使用。

I am building an application where data is retrieved from a third party system as a JSON string. I need to convert this JSON string to another JSON string with a different structure such that it can be used with pre-existing functions defined in a internal Javascript library.

理想情况下我希望能够使用Javascript在客户端计算机上执行此转换。

Ideally I want to be able to perform this conversion on the client machine using Javascript.

我已将JSONT视为实现此目的的一种方法,但该项目似乎没有主动维持:

I have looked at JSONT as a means of achieving this but that project does not appear to be actively maintained:

是否有实现这一目标的事实上的方法?或者我是否必须滚动自己的映射代码?

Is there a de facto way of achieving this? Or do I have to roll my own mapping code?

推荐答案

您不应该将JSON传递到内部JavaScript库。您应该将JSON解析为JS对象,然后迭代它,将其转换为新格式

You shouldn't be passing JSON into an internal JavaScript library. You should parse the JSON into a JS object, then iterate over it, transforming it into the new format

示例

var json = '[{"a": 1:, "b": 2}, {"a": 4:, "b": 5}]';
var jsObj = JSON.parse(json);
// Transform property a into aa and property b into bb
var transformed = jsObj.map(function(obj){
    return {
       aa: obj.a,
       bb: obj.b
    }
});

// transformed = [{aa:1, bb:2},{aa:4, bb:5}]

If you really want JSON you'd just call JSON.stringify(transformed)

这是另一个带有更复杂转变的答案

Here's another answer with an even more complicated transformation How to make a jquery Datatable array out of standard json?

这篇关于如何将JSON字符串转换为具有不同结构的JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:58