使用jQuery将JSON转换为XML

时间:2014-12-30 11:49:07

标签: jquery xml json

我需要将JSON转换为XML(使用jquery),但是这样:

如果我的JSON看起来像这样:

{
name: "sampleConfiguration",
description: "Configuration used for demonstration purposes"
version: "1.0",
parameters: [
    {
        name: "sampleParameter",
        description: "parameter description",
        value: "20",
        enabled: "1"
    },
    {
        name: "items",
        description: "parameter with subparameters",
        value:[
            {
                name: "item",
                description: "nested parameter",
                value: "13"
            },
            {
                name: "item",
                description: "nested parameter 2",
                value: "TEST"
            }
        ]
    }
]}

然后我应该将它转换为如下所示的XML:

<?xml version="1.0"?>
<sampleConfiguration version="1.0" description="Configuration used for demonstration purposes">
<params>
    <sampleParameter enabled="1" description="parameter description">20</sampleParameter>
    <items description="parameter with subparameters">
        <item description="nested parameter">13</item>
        <item description="nested parameter 2">TEST</item>
    </items>
</params>
</sampleConfiguration>

我一直在寻找JSON到XML转换代码,但我总是得到这样的XML(这是我不需要的):

<?xml version="1.0"?>
<name>sampleConfiguration</name>
<description>Configuration used for demonstration purposes</description>
<version>1.0</version>
<parameters>
   <name>sampleParameter</name>
   <description>parameter description</description>
   <value>20</value>
   <enabled>1</enabled>
</parameters>
<parameters>
   <name>items</name>
   <description>parameter with subparameters</description>
   <value>
      <name>item</name>
      <description>nested parameter</description>
      <value>13</value>
   </value>
   <value>
      <name>item</name>
      <description>nested parameter 2</description>
      <value>TEST</value>
   </value>
</parameters>

1 个答案:

答案 0 :(得分:0)

我认为你正在寻找: -

http://code.google.com/p/x2js/

此库提供XML到JSON(JavaScript对象),反之亦然javascript转换函数。该库非常小,不需要任何其他库。 :)