简体   繁体   中英

Get and Set Text Content from a JSON Object using JavaScript in node.js

Background information: I'm using node.js and this is a server side script.

That being said, here's the problem. I have a JSON Object result , when using eyes.inspect() , looks like

{
user: [
    {
        foods: {
            food: [
                {
                    #: 'McDonalds',
                    @: { type: 'string' }
                },
                {
                    #: 'Seafood Topped Salmon',
                    @: { type: 'string' }
                }
            ]
        },
        email: '****@******.edu',
        name: 'Leo'
    },
    {
        email: '****@******.edu',
        food-list: {
            food: [
                {
                    #: 'KFC',
                    @: { type: 'string' }
                },
                {
                    #: 'KGC',
                    @: { type: 'string' }
                }
            ]
        },
        name: 'Eric'
    }
]
}  

When calling console.log(result.user[0].foods.food[1]) , the output is { '#': 'Seafood Topped Salmon', '@': { type: 'string' } }

So is there a way to get and set the text content of a node just like Seafood Topped Salmon and get rid of the type attribute?

Some more information: that JSON is actually parsed from an XML document. In the original xml file, the food node looks like <food type="string">McDonalds</food> . I must keep the type="string" attribute and after I'm done with editing the JSON object, I will parse it back to xml.

您可以直接访问该嵌入式对象的文本来获取并将其设置为:

result.user[0].foods.food[1]['#']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM